JavaScript 在 ul 中查找 li 索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18295673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:22:08  来源:igfitidea点击:

JavaScript find li index within ul

javascripthtmlindexinghtml-lists

提问by Daniel Rasmuson

I'm trying to find the index of my list item by id in Javascript. For example I have list of 5 items and given an element I want to figure out which position it is in the list. Below is the code that I hope to build on.

我正在尝试通过 Javascript 中的 id 查找列表项的索引。例如,我有 5 个项目的列表,并给出了一个元素,我想弄清楚它在列表中的哪个位置。下面是我希望构建的代码。

It's using an onclick handler to find the element, which is working, I then just need to figure out the position of the element in the list 'squareList' in some way.

它使用 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);
    }
}

回答by Blender

To get the index, you can do:

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

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

And with jQuery, as you're already using cross-browser workarounds:

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

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

回答by Tuan Hoang

I have another solution and would like to share

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

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

You can verify here

你可以在这里验证

Reference: closest

参考:最近

回答by ncubica

With es6 and findIndex

使用 es6 和 findIndex

Transform the ul node list into an array: [...UL_ELEMENT.children]then use findIndexto check for the element you are looking for.

将 ul 节点列表转换为数组:[...UL_ELEMENT.children]然后用于findIndex检查您要查找的元素。

const index = [...UL_ELEMENT.childNodes].findIndex(item => item === LI_ELEMENT)

回答by sheplu

you can get all "li" in a list or array and then search the position with a simple loop

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