Getting the index of a list item with Jquery
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?
});
精彩评论