1

给定以下 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,则 的值为。如果他们悬停在 上,那么值将是,等等。在此先感谢!currListElementIndex0moe.jpg2

编辑:由于其他一些限制,我不能将 ID 添加到<li>元素或做任何其他显而易见的事情......我需要以<ul>某种方式获取(可能通过函数??)并找出那个索引<ul>算我一个。

4

2 回答 2

3

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

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

于 2012-05-02T12:28:09.750 回答
0
$(".imgThumbLi").live({
    mouseenter:
        function() {          
            var item=$(this);
            var src = $(this).children('img')[0].src;
            var currListElementIndex = item.index();
            alert(currListElementIndex);
        }
    }
);
于 2012-05-02T12:37:32.730 回答