问题描述
好吧,这里是我的javascript:
Alright, here is my javascript:
$().ready(function (){
$(".contact").hover(function (){
...
});
$(".contact").not('.contact[id="'+activeId+'"]').click(function (){
...
});
$(".contact_chooser_contact").click(function (){
...
$('.contacts').append('<div class="contact" id="'+id+'" title="'+phone+'">\
<div class="contact_img"><img src="src/default_face.png" width="64"/></div>\
<div class="contact_info" id="'+name+'">'+name+' <span class="sms_number">0</span></div>\
<div class="contact_last_sms">\
\
<!-- span class="last_sms_time"> echo $message[sizeof($message)-1]->time; </ -->\
</div>\
</div>');
...
});
});
请注意,如何在contact_chooser_contact点击处理程序中添加另一个.contact。联系人,但现在,当我将鼠标悬停在新的.contact上时,它没有做任何事情。我该如何解决这个问题,我知道它是因为我添加新的.contact之后,我没有重新启动'$(。contact).hover()',但有没有更简单的方法?
Notice, how in the "contact_chooser_contact" click handler, I append another ".contact" in ".contacts", but now when I hover over that new ".contact", it doesnt do anything like it is supposed to. How can I fix this problem, I understand that its because I havent reinitiated the '$(".contact").hover()' after I added the new ".contact", but is there an easier way?
推荐答案
您需要将事件与,使用它将绑定添加到DOM的任何元素和相应的选择器。使用 on()
over live()
的好处是您可以将上下文缩小到特定容器,而不是整个文档
。在我的示例中,我只是使用文档
作为上下文。
You need to bind the event with on(), using this will bind any element added to the DOM with the respective selector. The advantage of using on()
over live()
, is that you can narrow down the context to a specfic container, rather than the entire document
. In my example, I just use the document
as the context.
jQuery 1.7 使用
jQuery 1.7 use on()
$(document).on('mouseover', '.contact', function(){
...
});
小于 1.7 ,请使用
$(document).delegate('.contact', 'mouseover', function(){
...
});
小于 1.4.2 ,请使用
$('.contact').live('mouseover', function(){
...
});
这篇关于添加新div时,jQuery事件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!