简体   繁体   English

使用jQuery,如何在指定CSS类的同级元素中查找元素的索引

[英]Using jQuery, how to find the index of an element amongst its siblings of a specified CSS class

Given the following HTML: 鉴于以下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>

I'm trying to write the function showPath so that it returns the index of the parent div in relation to its siblings of class component . 我试图编写函数showPath以便它返回父div与其类component同级的索引。 So in the above sample, I would like the function to return 1 . 因此,在以上示例中,我希望函数返回1

I've got this far, but it returns 2 ; 我已经走了很远,但是它返回2 I don't know what to do to ignore the div of class somethingelse 我不知道该怎么办忽略div类的somethingelse

function showPath(element) {
    var component = $(element).closest('.component');
    alert(component.index());
}

Try this(haven't tested): 试试这个(尚未测试):

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

A quick and simple extension for jQ to turn this process into a method: jQ的快速简单扩展,可以将这个过程变成一种方法:

$.fn.getIndex = function(){
    var index = $(this).parent().children().index( $(this) );
    return index;
}

Run this on document.ready or wrap it in a function and run it that way (probably cleaner). 在document.ready上运行它或将其包装为一个函数并以这种方式运行(可能更干净)。

Usage is as simple as 用法很简单

var index_for_element = $('.thing-you-want-index-for').getIndex();

You can do this. 你可以这样做。

$('input').click(function() {
    var component = $(this).closest('.component');
    alert(component.parent().children(".component").index(component));
})

Check working example at http://jsfiddle.net/Qzk6A/2/ http://jsfiddle.net/Qzk6A/2/中查看工作示例

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

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