【问题标题】:How to determine the index of the element in its parent node?如何确定元素在其父节点中的索引?
【发布时间】:2011-11-20 07:56:00
【问题描述】:

示例代码如下:

<div>
    <div>
    </div>
    <div>
    </div>
    <div>
    </div>
     ....

</div>

我只需要在父div中找到内部div的索引,作为this传递给函数。

附言我检查了另一个相同的问题: Is it possible to get element's numerical index in its parent node without looping?

但是建议的方法对我不起作用.. Is it possible to get element's numerical index in its parent node without looping?

【问题讨论】:

    标签: javascript dom


    【解决方案1】:

    这是一个使用纯 JS(无 jQuery)的工作示例:http://jsfiddle.net/jfriend00/xgk4y/。点击任一 div 可查看从countPrevSiblings() 返回的索引。

    以及其中的代码:

    function countPrevSiblings(elem) {
        var i = 0;
        while((elem = elem.previousSibling) != null) {
            // count element nodes only
            if (elem.nodeType == 1) {
                ++i;
            }
        }
        return i;
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用index() jquery 函数获取索引,如果这不适合您,请再解释一下您的问题。

      示例:$(this).index($(this).siblings());

      【讨论】:

      • jquery 在这个问题上没有被标记,这通常意味着 OP 想要一个纯 js 解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多