Jquery - 通过悬停从列表中获取div编号

时间:2011-08-19 12:18:02

标签: javascript jquery list count hover

如何通过将鼠标悬停在div上来获取数字?

HTML

<div id="log"></div>

<div id="myList">

    <div class="divHV">One </div>
    <div class="divHV">Two</div>
    <div class="divHV">3 </div>

    <div class="divHV">Blub </div>
    <div class="divHV">Peter</div>
    <div class="divHV">6 House</div>

    <div class="divHV">last one is 7</div>    

</div>

JS

$(document).ready(function() {

    $('.divHV').hover(function()
    {
        XX = '';
        $('#log').html('This is the div number '+XX+' <br />');

    }, function ()
    {
        $('#log').html('');
    });     

});

工作场所
http://jsfiddle.net/9R4aC/2/

2 个答案:

答案 0 :(得分:3)

XX = $(this).index();

但是从0开始,如果你愿意,可以加+1。

http://jsfiddle.net/9R4aC/2/

答案 1 :(得分:2)

$(document).ready(function() {

    $('.divHV').each(function(i) {
        $(this).hover(function() {
            XX = i;
            $('#log').html('This is the div number ' + XX + ' <br />');

        }, function() {
            $('#log').html('');
        });

    });

});

http://jsfiddle.net/9R4aC/3/