我试图在 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();
})
});
关于JavaScript 在 ul 中查找 li 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18295673/