javascript - 如何查找列表项的索引(ul-li)?

标签 javascript jquery html jquery-selectors

我有一个 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/

相关文章:

javascript - 使用 jquery ajax 发送关联数组

c# - 在 ASP.NET 中通过 jQuery/ajax 获取复杂对象

html - 左对齐右对齐div,以防没有媒体查询的空间太少

html - 3 列 : one with max-width, 其他两列最小宽度

jquery - 克隆包含选择的行,并克隆选择的值

javascript - 将字符串发送到 UnityWebGL jslib

JavaScript - 旋转 Canvas 图像, Angular 被剪掉

javascript - 如何在鼠标移出时从当前帧恢复 css3 关键帧动画?

html - novalidate HTML 属性有什么作用?

javascript - Bootstrap 表悬停不起作用