开发者

Getting the index of a list item with Jquery

开发者 https://www.devze.com 2022-12-09 09:14 出处:网络
I\'m trying to find out the index number of the last list item but the jquery I\'m using keeps returning -1. This is the JS and the html that I\'m using.

I'm trying to find out the index number of the last list item but the jquery I'm using keeps returning -1. This is the JS and the html that I'm using.

var index = $('#imageThumbnails li:last').index(this);

<div i开发者_运维百科d="imageThumbnails">
   <ul class="gallery_demo_unstyled">
      <li class="active"><img src="test-img.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img2.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img3.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img4.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img5.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img6.jpg" width="394" height="394" alt=" " /></li>
      <li><img src="test-img7.jpg" width="394" height="394" alt=" " /></li>
    </ul>
 </div>

Thanks for your help.


You need to call index on the collection, passing in a sub-item of that collection.

var items = $('#imageThumbnails li');
var lastItem = $('#imageThumbnails li:last');
var index = items.index(lastItem);

If you are in a click function handler you could do something like this:

var items = $('#imageThumbnails li').click(function() {
    var index = items.index(this);

    // now that I know where I am, why am I here?
});
0

精彩评论

暂无评论...
验证码 换一张
取 消