获取具有ID的li索引? [英] Get index of li with ID?

查看:134
本文介绍了获取具有ID的li索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个可排序的列表:

I have this sortable list:

            <ul id="sortable">
              <li id="Item1"><img src="../../../../IMAGES/04_01/P2_0401_18.jpg" /></li>
              <li id="Item2"><img src="../../../../IMAGES/04_01/P2_0401_20.jpg" /></li>
              <li id="Item3"><img src="../../../../IMAGES/04_01/P2_0401_22.jpg" /></li>
              <li id="Item4"><img src="../../../../IMAGES/04_01/P2_0401_24.jpg" /></li>
              <li id="Item5"><img src="../../../../IMAGES/04_01/P2_0401_26.jpg" /></li>
              <li id="Item6"><img src="../../../../IMAGES/04_01/P2_0401_28.jpg" /></li>
            </ul>

,当然,当用户移动项目时,每个项目ID的索引也会更改.我想做的是将项目的新索引存储在单独的变量itemIndex1, itemIndex2, etc中,这样我就可以在以后运行的函数中检查它们的位置.

and of course, when the users move the items, the index of each item ID changes. What I'm trying to do is store the new indexes of the items in separate variables itemIndex1, itemIndex2, etc so I will be able to check their positions in a function that runs later on.

这是引起我难题的代码:

This is the code that's causing my conundrum:

var itemIndex1 = $('#sortable li').index($('#sortable li:nth-child(1)'));
var itemIndex2 = $('#sortable li').index($('#sortable li:nth-child(2)'));
var itemIndex3 = $('#sortable li').index($('#sortable li:nth-child(3)'));
var itemIndex4 = $('#sortable li').index($('#sortable li:nth-child(4)'));
var itemIndex5 = $('#sortable li').index($('#sortable li:nth-child(5)'));
var itemIndex6 = $('#sortable li').index($('#sortable li:nth-child(6)'));

我在这里关于stackoverflow的另一个问题中找到了该解决方案,但是它实际上并不适合我的目的,因为每个itemIndex都简单地返回每个li子项的索引,而不管其ID如何. itemIndex1将始终返回0itemIndex2将始终返回1,依此类推.

I found this solution in another question here on stackoverflow, but it doesn't really suit my purposes because each itemIndex simply returns the index of each li child, regardless of its ID. itemIndex1 will always return 0, itemIndex2 will always return 1, etc.

例如,如果用户将其拖动到0索引,我希望能够获得#Item4的索引.

I'd like to be able to get the index of #Item4 for example, if the user has dragged it to the 0 index.

推荐答案

只需在 .index 上使用它是自己的:

Just use .index on it's own:

var idx = $("#Item4").index();

如果没有参数传递给.index()方法,则返回值为 一个整数,指示第一个元素在 jQuery对象相对于其同级元素

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements

这篇关于获取具有ID的li索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆