使用 Jquery 获取列表项的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1633205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:53:15  来源:igfitidea点击:

Getting the index of a list item with Jquery

jquerycss-selectors

提问by Paul Sheldrake

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.

我试图找出最后一个列表项的索引号,但我使用的 jquery 一直返回 -1。这是我正在使用的 JS 和 html。

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

<div id="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.

谢谢你的帮助。

回答by joshperry

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

您需要在集合上调用 index ,传入该集合的一个子项。

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?
});