admin管理员组

文章数量:1221774

Given the following 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. So in the above sample, I would like the function to return 1.

I've got this far, but it returns 2; I don't know what to do to ignore the div of class somethingelse

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

Given the following 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. So in the above sample, I would like the function to return 1.

I've got this far, but it returns 2; I don't know what to do to ignore the div of class somethingelse

function showPath(element) {
    var component = $(element).closest('.component');
    alert(component.index());
}
Share Improve this question edited Dec 4, 2017 at 17:37 Nathan Arthur 9,0967 gold badges64 silver badges83 bronze badges asked Mar 12, 2011 at 0:20 sandysandy 9131 gold badge11 silver badges25 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 9

A quick and simple extension for jQ to turn this process into a method:

$.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).

Usage is as simple as

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

Try this(haven't tested):

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

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/

本文标签: