【问题标题】:JavaScript find li index within ulJavaScript 在 ul 中查找 li 索引
【发布时间】:2013-08-18 04:21:48
【问题描述】:

我正在尝试通过 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);
    }
}

【问题讨论】:

  • 如果您真的需要帮助,请附上您的 HTML 标记。您最好的选择可能是 jsFiddle。 squareList<ul> 的 ID 吗?你的<li> 元素有共享类吗?有嵌套列表吗?所有这些问题的答案都将通过 jsFiddle 给出。
  • 尝试this之类的东西是不可接受的
  • @Harry: value 会使 HTML 无效。 data-value,不过……也许吧。
  • @cHao:同意,我只是想指出一种可能的方式(不是确切的方式)。但正确,它可能会产生误导:(我现在已经更新了。
  • @Harry 非常感谢 Harry,非常有帮助。

标签: javascript html indexing html-lists


【解决方案1】:

要获取索引,可以这样做:

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

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

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

【讨论】:

  • 简直是最好的!
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    使用 es6 和 findIndex

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

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          猜你喜欢
          • 2021-11-14
          • 1970-01-01
          • 2022-12-05
          • 2014-09-15
          • 2013-12-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-18
          • 1970-01-01
          相关资源
          最近更新 更多