JavaScript在ul中查找li索引

问题描述 投票:3回答:3

我正在尝试通过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);
    }
}
javascript html indexing html-lists
3个回答
12
投票

要获取索引,您可以执行:

Array.prototype.indexOf.call(squareList.childNodes, target)

以及使用jQuery,因为您已经在使用跨浏览器的解决方法:

$(document).ready(function() {
    $('#squareList li').click(function() {
        var index = $(this).index();
    })
});

0
投票

我还有另一种解决方案,想分享

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);
};

您可以验证here

参考:closest


-1
投票

您可以获取列表或数组中的所有“ li”,然后通过简单的循环搜索位置

© www.soinside.com 2019 - 2024. All rights reserved.