gpt4 book ai didi

jQuery - 查找相对于其容器的元素索引

转载 作者:行者123 更新时间:2023-12-01 00:47:03 26 4
gpt4 key购买 nike

这是我的 HTMl 结构:

<div id="main">
<div id="inner-1">
<img />
<img />
<img />
</div>

<div id="inner-2">
<img />
<img class="selected" />
<img />
</div>

<div id="inner-3">
<img />
<img />
<img />
</div>
</div>

我想做的是获取 img.selected 元素相对于 #main div 的索引。因此,在此示例中,索引应为 4(假设基于 0 的索引)而不是 1。

我获取索引的常用方法是使用 $element.prevAll().length 但显然,这将返回相对于 #inner-2 div 的索引。

我尝试使用 $('img.selected').prevAll('#main').length 但返回 0 :/

最佳答案

这会起作用;它在 #main 内的所有 img 标记集中查找所选图像的索引。

$('#main img').index('img.selected');

关于jQuery - 查找相对于其容器的元素索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2619415/

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