jQuery悬停不适用于动态元素 [英] jQuery hover not working with dynamic elements
问题描述
< p>< p> ; div id ='link_delete_holder'style ='position:absolute; left:590px; top:10px'>
< img id ='link_delete'src ='images / account_related / icons / link_delete.png'/>
< / div>
我希望该图像在悬停时发生变化,因此我使用以下代码:
$('#link_delete')。hover(function(){
$(this).attr('src','images (){
$(this).attr('src','images / account_related / icons / link_delete.png');
});
现在,问题是它只能在第一条记录(第一条显示的link_delete图像) ,并且似乎不适用于其他图像。
如果您要创建动态数据,请不要使用ID来抓取它们,因为它无效HTML有两个具有相同ID的元素。
< div id ='link_delete_holder'style ='position:绝对的;左:590px;顶部:10px的'>
< img class ='link_delete'src ='images / account_related / icons / link_delete.png'/>
< / div>
另外,Anoop Joshi指出你不能直接使用 $(' #link_delete')。hover(...);
你需要使用一个委托并使用我从上面所说的添加基于类的委托而不是ID,并且应该使用 mouseenter
和 mouseleave
,这基本上就是 .hover(func(),func())< $ {
$('。link_delete')。on({
mouseenter:function (){
$(this).attr('src','images / account_related / icons / link_delete_h.png');
},
mouseleave:function(){
$(this).attr('src','images / account_related / icons / link_delete.png');
}
});
编辑:
a href =http://jsfiddle.net/qgTzE/4/ =nofollow> jsFiddle 已经动态创建的图片在悬停时<
Im getting data out of a database, and based on the number of matches, I want to output this:
<div id='link_delete_holder' style='position:absolute;left:590px;top:10px'>
<img id='link_delete' src='images/account_related/icons/link_delete.png'/>
</div>
I want that image to be changing on hover, so I use this code:
$('#link_delete').hover(function(){
$(this).attr('src', 'images/account_related/icons/link_delete_h.png');
}, function(){
$(this).attr('src', 'images/account_related/icons/link_delete.png');
});
Now, the problem is it only works on the first record (the first link_delete image that gets displayed), and seems like it doesn't apply to other images.
If you're going to have dynamic data created, don't use an ID to grab them because it is not valid HTML to have two elements with the same ID. Use a class with the same name and it will work fine.
<div id='link_delete_holder' style='position:absolute;left:590px;top:10px'>
<img class='link_delete' src='images/account_related/icons/link_delete.png'/>
</div>
Also, as Anoop Joshi points out you cannot use a direct $('#link_delete').hover(...);
you need to use a delegate and using what I said from above add the delegate based on the class not the ID, and you should use mouseenter
and mouseleave
as that is essentially what .hover(func(), func())
is doing.
$('.link_delete').on({
mouseenter: function () {
$(this).attr('src', 'images/account_related/icons/link_delete_h.png');
},
mouseleave: function () {
$(this).attr('src', 'images/account_related/icons/link_delete.png');
}
});
EDIT:
Added a working jsFiddle that has dynamically created images that will on hover
change the image and then back when you're done hovering.
这篇关于jQuery悬停不适用于动态元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!