Why is .index() always returning 0

后端 未结 3 1672
眼角桃花
眼角桃花 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

      , which if I'm not mistaken, is invalid markup without include
    • around the anchors.

      I would change your HTML to this:

      
      

      this is a

      this is b

      this is c

      this is d

      And you JS to this:

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

提交回复
热议问题