【问题标题】:How can i get the index of the child node clicked如何获取单击的子节点的索引
【发布时间】:2019-09-29 09:43:33
【问题描述】:

我在一个 div 容器中有 3 个 span 项, 当用户单击任何项​​目时 在容器中,因为 div(container) 是 (item) span 元素的 parentNode。我想点击(item)span 元素的索引。

"如何获取被点击的子节点的索引"

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你可以有这样的东西:

    document.querySelector("div").onclick = ({target}) => {
      let index = 0;
      while (target = target.previousElementSibling) {
        index++;
      }
    
      console.log(index);
    }
    

    逻辑如下:你添加一个事件监听器到容器(div,假设你只有span作为孩子,否则你需要过滤target只对span做出反应,或者添加监听器到每个跨度),然后从单击的span 获得前一个兄弟元素,直到没有任何兄弟元素——因此你到达容器的第一个子元素——并返回迭代计数。

    另一种方法可能是:

    const getIndex = (target, list) =>
      Array.prototype.indexOf.call(list, target)
    
    const div = document.querySelector("div");
    const span = div.querySelectorAll("span");
    
    console.log(getIndex(span[1], span)) // 1
    

    这更通用:它为您提供对象在类似数组的对象中的位置,因此它适用于 NodeList,但不仅适用于 NodeList。另外,您可以传递任意列表。

    用这个函数替换前面的例子,你会得到类似的东西:

    document.querySelector("div").onclick = ({target}) => {
      console.log(getIndex(target, target.parentNode.children));
    }
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      其实很简单, 如果您使用的是jquery,,那么它就像

      $("span").click(function(){
          console.log($(this).index())
      });
      

      或者,如果您使用的是纯 javascript,这应该可以完成这项工作

      $("span").click(function(){
          console.log(Array.from(this.parentNode.children).indexOf(this));
      });
      

      【讨论】:

        【解决方案3】:

        一个简单的解决方案可能是。在构建添加数据属性时以及当用户单击获取它时。

        // Set arribute:
        $("span").attr("data-id",index++);
        OR
        $(this).attr("data-id",index++);
        // Get arribute:
        $(this).attr("data-id");
        

        【讨论】:

          猜你喜欢
          • 2011-08-20
          • 2023-01-29
          • 2023-03-14
          • 2020-10-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多