简体   繁体   English

JavaScript 在 ul 中查找 li 索引

[英]JavaScript find li index within ul

I'm trying to find the index of my list item by id in Javascript.我试图在 Javascript 中通过 id 找到我的列表项的索引。 For example I have list of 5 items and given an element I want to figure out which position it is in the list.例如,我有 5 个项目的列表,并给出了一个元素,我想弄清楚它在列表中的哪个位置。 Below is the code that I hope to build on.下面是我希望构建的代码。

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

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

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参考: 最近

With es6 and findIndex使用 es6 和 findIndex

Transform the ul node list into an array: [...UL_ELEMENT.children] then use findIndex to check for the element you are looking for.将 ul 节点列表转换为数组: [...UL_ELEMENT.children]然后使用findIndex检查您要查找的元素。

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

使用扩展运算符 [...] 将 ul 元素的子元素转换为数组,然后使用 Array.prototype.indexOf() 方法将子元素作为参数传递。

const index = [...UL_ELEMENT.children].indexOf(LI_ELEMENT);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM