我正在尝试通过 Javascript 中的 id 查找列表项的索引。例如,我有 5 个项目的列表,给定一个元素,我想找出它在列表中的位置。下面是我希望构建的代码。
它使用 onclick 处理程序来查找正在工作的元素,然后我只需要以某种方式找出列表“squareList”中元素的位置。
window.onload=function(){
function getEventTarget(e){
var e=e || window.event;
return e.target || e.srcElement;
}
function selectFunction(e){
var target=getEventTarget(e);
alert(target.id);
}
var squareList=document.getElementById('squareList');
squareList.onclick=function(e){
selectFunction(e);
}
}
要获取索引,您可以执行以下操作:
Array.prototype.indexOf.call(squareList.childNodes, target)
对于 jQuery,因为您已经在使用跨浏览器解决方法:
$(document).ready(function() {
$('#squareList li').click(function() {
var index = $(this).index();
})
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)