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、 の値はcurrListElementIndexになります0。の上にカーソルを置いてmoe.jpgいた場合、値は2などになります。よろしくお願いします。

編集:他のいくつかの制約のため、<li>要素に ID を追加したり、他のことを行うことはできません...何らかの方法で (おそらく<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 に答える