gpt4 book ai didi

javascript - 设置 HTML 内容后立即附加事件

转载 作者:行者123 更新时间:2023-11-30 10:48:54 24 4
gpt4 key购买 nike

这是我在函数中用于分页的 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
});

但是 hover 事件根本不起作用,我认为这是因为 DOM 还没有准备好造成的!

为了解决这个问题,我设置了一个像这样的计时器:

$('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);

我问这个问题是因为我确定这不是在 html 方法之后立即附加事件的正确方法(也许它不起作用!)。

si 我希望有人告诉我正确的方法。

最佳答案

你会想要使用实时 mouseover mouseleave 事件

$("div#my_div").live({
mouseenter: function()
{

},
mouseleave: function()
{

}
}
);

或者你可以这样做:

$('div#my_div').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
// do something on mouseover
} else {
// do something on mouseout
}
});

更新

在较新版本的 jQuery 中,您可以这样做

$('body').on('mouseover','#my_div', function(){});
$('body').on('mouseout', '#my_div', function(){});

关于javascript - 设置 HTML 内容后立即附加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6680265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com