gpt4 book ai didi

jquery - 如何在包装器元素中获取具有类名的当前元素的索引

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:12 26 4
gpt4 key购买 nike

这是html,

<div id="wraper">
<div>
<div class="test">1</div>
</div>
<div>
<div class="test">2</div>
</div>
<div>
<div class="test">3</div>
</div>
<div>
<div class="test">4</div>
</div>
<div>
<div class="test">5</div>
</div>
</div>

$("#wraper").find(".test").eq(2);这将选择 wraper 中的第 3 个 test

我需要在单击 .test div 时获取该索引(我已将其作为参数传递给 eq())。

当我点击类名为 test 的 div 时,我需要在 wraper div 中获取该 div 的索引。

$(".test").click(function() {
alert($(this).index());
});

此代码将始终返回 0,因为 test div 具有父 div。所以如果我使用 $(this).parent().index(),它将返回正确的索引。

还有其他替代方法吗?因为在我的真实场景中可能会有多个级别的 parent 。

Fiddle

最佳答案

您可以使用 .index() 的第 3 版它根据调用 .index() 的元素集返回 passes 项目的索引

var $tests = $(".test").click(function () {
alert($tests.index(this));
});

演示:Fiddle

关于jquery - 如何在包装器元素中获取具有类名的当前元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25157184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com