使用jQuery,如何在指定CSS类的兄弟之间找到元素的索引

san*_*ndy 6 javascript jquery

给出以下HTML:

<div class="component">
    <div class="component">
        <div class="component">
        </div>
    </div>
    <div class="component">
        <div class="somethingelse">
        </div>
        <div class="component">
        </div>
        <div class="component">
            <input type="button" value="Get Path" onclick="showPath(this)" />
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在尝试编写函数,showPath以便它返回div与其兄弟类相关的父元素的索引component.所以在上面的示例中,我希望函数返回1.

我已经走到了这一步,但它又回归了2; 我不知道该做什么来忽略div课堂somethingelse

function showPath(element) {
    var component = $(element).closest('.component');
    alert(component.index());
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*ndu 6

试试这个(尚未测试):

function showPath(element) {      
  var component = $(element).closest('.component');     
  alert(component.parent().find(".component").index(component)); 
} 
Run Code Online (Sandbox Code Playgroud)

  • 我想你想要`.children(".component")`,因为`.find()`将返回任何级别的所有后代. (3认同)

dcl*_*901 6

jQ的快速简单扩展,可将此过程转换为方法:

$.fn.getIndex = function(){
    var index = $(this).parent().children().index( $(this) );
    return index;
}
Run Code Online (Sandbox Code Playgroud)

在document.ready上运行它或将其包装在一个函数中并以这种方式运行(可能更干净).

用法很简单

var index_for_element = $('.thing-you-want-index-for').getIndex();
Run Code Online (Sandbox Code Playgroud)