Why is .index() always returning 0

后端 未结 3 1651
眼角桃花
眼角桃花 2021-01-18 05:23

I\'m confused as to why .index() is returning 0 in this code. Shouldn\'t it return the index of where it\'s found in the array of jquery objects?

相关标签:
3条回答
  • 2021-01-18 05:32

    Your anchor elements don't have any siblings, so they're all index 0. They're all nested in their own <ul>, which if I'm not mistaken, is invalid markup without include <li> around the anchors.

    I would change your HTML to this:

    <div id="nav">
        <ul>
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li><a href="#">Link 3</a></li>
            <li><a href="#">Link 4</a></li>
        </ul>
    </div>
    <div class="parent">
        <div class="a">
            <p>this is a</p>
        </div>   
        <div class="b">
            <p>this is b</p>
        </div>
        <div class="c">
            <p>this is c</p>
        </div>
        <div class="d">
            <p>this is d</p>
        </div>
    </div>
    

    And you JS to this:

    $('.parent  div').hide();
    
    $('#nav a').click(function() {
        // Notice, I'm going up to the parent <li> and then calling index().
        var $div = $('.parent > div').eq($(this).parent().index());
        $div.show();
        $('.parent > div').not($div).hide();
    });​
    

    Working example

    0 讨论(0)
  • 2021-01-18 05:53

    index is always 0 because the <a> is the 1st child in its parent (the <ul>).

    Try getting the <ul>'s index instead.

    $(this).parent().index()
    

    NOTE: Your HTML isn't valid. The only valid children of <ul>s are <li>s.

    0 讨论(0)
  • 2021-01-18 05:55

    Another reason that .index() could return 0 is if you are using it like so:

    $('matched elements').click(function(){
        console.log($(this).index()); // will be 0 in some cases
    });
    

    Correct way:

    $('matched elements').click(function(){
        console.log($('matched elements').index($(this))); // will be the index within set of matched elements
    });
    
    0 讨论(0)
提交回复
热议问题