[英]jQuery: attach an event immediately after setting up the HTML content
first this is an exemple of my jQuery code that I use in a function to do pagination:首先,这是我在 function 中使用的 jQuery 代码进行分页的示例:
// new_content is a variable that holds the html I want to add to a div
$('div#my_div').html(new_content);
$("div#my_div a.details").hover(function(){
$(this).fadeIn(); //code to execute when the mouse get in
}, function(){
$(this).fadeOut(); //code to execute when the mouse get out
});
BUT the hover event does not work at all, and I belive that this is caused because the DOM is not ready yet!但是 hover 事件根本不起作用,我相信这是因为 DOM 还没有准备好!
and to get around this I used set up a timer like this:为了解决这个问题,我使用了这样的计时器:
$('div#my_div').html(new_content);
window.setTimeout(
$("div#my_div a.details").hover(function(){
$(this).fadeIn(); //code to execute when the mouse get in
}, function(){
$(this).fadeOut(); //code to execute when the mouse get out
});
,100);
I asked this question because I'm sure that this is not the right way to attach an event immediatly after the html method (maybe it didn't it's work.).我问这个问题是因为我确定这不是在 html 方法之后立即附加事件的正确方法(也许它没有工作。)。
si I hope someone show me the right way to do it. si 我希望有人告诉我正确的方法。
You would want to use the live mouseover
mouseleave
events您会想要使用实时mouseover
mouseleave
事件
$("div#my_div").live({
mouseenter: function()
{
},
mouseleave: function()
{
}
}
);
Alternately you could do:或者,您可以这样做:
$('div#my_div').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});
UPDATE更新
In newer versions of jQuery you can do it like this在 jQuery 的较新版本中,您可以这样做
$('body').on('mouseover','#my_div', function(){});
$('body').on('mouseout', '#my_div', function(){});
Maybe you need to use the live()
method.也许您需要使用live()
方法。 As you can read here , it seems that you will need to separate the two events:正如您可以在此处阅读的,您似乎需要将这两个事件分开:
.live("mouseenter", function() {...})
.live("mouseleave", function() {...});
UPDATE: Someone voted me up, so if someone gets here, I recommend to read the on()
documentation ( here ) as live
was deprecated long ago.更新:有人投票支持我,所以如果有人到这里,我建议阅读on()
文档(这里),因为live
很久以前就被弃用了。 Also, it may be interesting to see mouseenter()
( link ) and mouseleave()
( link ).此外,看看mouseenter()
( link ) 和mouseleave()
( link ) 可能会很有趣。 The idea is the same as with live
.这个想法与live
相同。
you can check out.live function of jquery.您可以查看.live function 的 jquery。 Here is the link http://api.jquery.com/live/这是链接http://api.jquery.com/live/
It is better to use a delegate rather than live, as live is essentially a delegate on the document.body causing it to have to bubble much longer.最好使用委托而不是 live,因为 live 本质上是 document.body 上的委托,导致它必须冒泡更长的时间。
Here is an example using a delegate: http://jsfiddle.net/Akkuma/wLDpT/这是使用委托的示例: http://jsfiddle.net/Akkuma/wLDpT/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.