如果我有这样的 html 结构:
<div id="parent">
<div class="child first">
<div class="sub-child"></div>
</div>
<div class="child second">
<div class="sub-child"></div>
</div>
<div class="child third">
<div class="sub-child"></div>
</div>
</div>
我有一个通过 ($('#parent.child')).click()
定义的点击处理程序然后我点击类为 second
的 div (first, second, third
只是添加了类以使演示更清晰)是否有一种简单的方法来获得数字 1,因为它是第二个 child ? (基于 0 的索引)?
类似于 $(this).index
最佳答案
看看 jQuery API。你建议的方法,index
, 完全正确:
$('#parent .child').click(function() {
var index = $(this).index();
});
来自文档:
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.
另请注意,我已根据您的示例对选择器进行了轻微更改。不过,我猜那只是您问题中的错字。 #parent.child
将查找 ID 为“parent”且类为“child”的元素,但实际上您希望 #parent.child
(注意空格)查找属于 ID 为“parent”的元素的后代的类为“child”的元素。
关于javascript - 使用 jQuery 找到 child 的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10460815/