我有一个 jQuery 对象,它是一个 HTML li 元素。如何找到它在其父 ul 上下文中的索引是什么?
所以如果我有这个:
<ul>
<li>abc</li>
<li id="test">def</li>
<li>hij</li>
</ul>
这个对象:
$("test")
有没有办法获取该元素的索引号。在这种情况下,它将是 1(如果将 0 算作第一个索引)。我可以用 $("test").parent() 做些什么吗?
最佳答案
您可以简单地使用$("#test").index()
。请注意 id 选择器 #
的使用。
何时 .index()
调用时不带任何参数,
the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
在这种情况下,这将是 1 -- see it in action .
关于javascript - 如何查找列表项的索引(ul-li)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10857795/