我正在尝试在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);
}
}发布于 2013-08-18 12:30:05
要获取索引,您可以执行以下操作:
Array.prototype.indexOf.call(squareList.childNodes, target)对于jQuery,因为您已经在使用跨浏览器的变通方法:
$(document).ready(function() {
$('#squareList li').click(function() {
var index = $(this).index();
})
});发布于 2020-03-08 11:02:08
我有另一个解决方案,想和大家分享
function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
let ul = document.getElementById('squareList');
ul.onclick = function(event) {
let target = getEventTarget(event);
let li = target.closest('li'); // get reference by using closest
let nodes = Array.from( li.closest('ul').children ); // get array
let index = nodes.indexOf( li );
alert(index);
};你可以验证
这里
参考资料:
最接近
发布于 2020-04-09 07:24:26
使用es6和findIndex
将ul节点列表转换为数组:
然后使用
检查您正在查找的元素。
const index = [...UL_ELEMENT.childNodes].findIndex(item => item === LI_ELEMENT)https://stackoverflow.com/questions/18295673
复制相似问题