ID不同但类名相同的问题


different IDs but same class name problem

我显示了一行具有相同div类名但不同div ID的项

当我将鼠标悬停在项目上时,我试图使用jquery来捕获不同的ID。但现在,我悬停在上面的每个项目,我只得到最新的ID,而不是悬停时得到的特定ID。

这是我的php:

while($row = mysql_fetch_array($sql)){
$id = $row['id'];
echo "<div class='row'><div class='a' id='a_".$id."'>do something</div></div>";
}

假设这将有10行,并且每行div都有唯一的ID

这是我的jquery:

 $('.row').hover(function(){
    var a = $('.a').attr('id');
    alert(a);
    }, function(){
});

有人能帮我弄清楚为什么我只得到最新的ID(都是一样的(,而不是不同的ID吗?

谢谢!

更改

var a = $('.a').attr('id');

var a = $('.a', this).attr('id');

使用前者只获得最后一个ID的原因是查询没有指定任何上下文,这意味着您在整个文档中搜索a类。在多元素jQuery对象上使用attr()方法时,它将只返回最后一个对象的属性。

此处演示-http://jsfiddle.net/h7QDX/

var a = $('.a', this).attr('id');

如果要在当前上下文中查找特定元素,则需要提供上下文(this(。

假设php脚本的渲染标记类似于以下内容:

<div id="currentTarget"></div> <!-- just for the purposes of the demo -->
<div class='row'><div class='a' id='a_1'>do something</div></div>
<div class='row'><div class='a' id='a_2'>do something</div></div>
<div class='row'><div class='a' id='a_3'>do something</div></div>
<div class='row'><div class='a' id='a_4'>do something</div></div>
<div class='row'><div class='a' id='a_5'>do something</div></div>
<div class='row'><div class='a' id='a_6'>do something</div></div>

以下jQuery使用hover():检索.a元素的id

$('.a').hover(
    function(){
        $('#currentTarget').text(this.id);
        // retrieve the id with: this.id
    },
    function(){
        $('#currentTarget').text('');
    });

JS Fiddle演示。

显然,上述内容依赖于悬浮的.a元素本身;如果您想通过将鼠标悬停在.row元素上来触发相同的操作,那么:

$('.row').hover(
    function(){
        $('#currentTarget').text($(this).find('.a').attr('id'));
        // retrieve the id with: $(this).find('.a').attr('id')
    },
    function(){
        $('#currentTarget').text('');
    });

JS Fiddle演示。

Try,

$('.row').hover(function(){
    var a = $('.a').attr('id');
    alert($('.a',this).attr('id'));
    }, function(){
});

此处:var a = $('.a').attr('id');您获得类为"a"的第一个项目你想要$(这个(

像这样:

$('.row').hover(function(){
    var a = $(this).attr('id');
    alert(a);
    }, function(){
});

如果您希望div开关包含'.row',请使用.eparent(多次作为div(

像这样:

$('.row').hover(function(){
    var a = $(this).parent().attr('id');
    alert(a);
    }, function(){
});