gpt4 book ai didi

javascript - jQuery:如何获取列表元素的索引

转载 作者:行者123 更新时间:2023-11-30 13:20:22 24 4
gpt4 key购买 nike

给定以下 HTML:

<ul>
<li class="imgThumbLi">
<img src="larry.jpg"/>
</li>
<li class="imgThumbLi">
<img src="curly.jpg"/>
</li>
<li class="imgThumbLi">
<img src="moe.jpg"/>
</li>
</ul>

然后,每当有人将鼠标悬停在这些 <img> 之一上时,我就会有一些 jQuery 来处理元素:

$(".imgThumbLi").live({
mouseenter:
function() {
// Obtain the source of the current image we're hovering over.
var src = $(this).children('img')[0].src;

// Now I need to know which <li> the "current" (one we're hovering
// over) image's parent <li> we're in, as a zero-based index
// of the <ul>.
var currListElementIndex = ????
}
}
);

因此,如果用户将鼠标悬停在 larry.jpg 上, 那么 currListElementIndex 的值将是 0 .如果他们悬停在 moe.jpg 上,则该值为 2等。提前致谢!

编辑:由于其他一些限制,我无法将 ID 添加到 <li>元素或做任何其他明显的事情......我需要获得 <ul>以某种方式(也许通过 parent 函数??)找出那个 <ul> 的索引我在。

最佳答案

由于 live 函数应用于 "li",您可以使用 $(this).index() 获取其索引。所以

var currListElementIndex = $(this).index() 返回索引

关于javascript - jQuery:如何获取列表元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10413731/

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