jQuery:设置HTML内容后立即附加事件

jQuery:设置HTML内容后立即附加事件,jquery,javascript-events,javascript,Jquery,Javascript Events,Javascript,首先,这是我在函数中用于分页的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 }

首先,这是我在函数中用于分页的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方法之后立即附加事件的正确方法,也许它不起作用


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

你会想使用mouseover mouseleave活动现场直播

或者你可以做:

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

您可能希望使用实时mouseover mouseleave事件

或者你可以做:

$('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(){});
也许你需要使用现场方法。如您所知,您似乎需要将这两个事件分开:

.live("mouseenter", function() {...})
.live("mouseleave", function() {...});
更新:有人投票支持我,所以如果有人到了这里,我建议阅读关于live的文档,因为live早就被弃用了。此外,看到mouseenter和mouseleave可能会很有趣。这个想法和live是一样的。

也许你需要使用live方法。如您所知,您似乎需要将这两个事件分开:

.live("mouseenter", function() {...})
.live("mouseleave", function() {...});

更新:有人投票支持我,所以如果有人到了这里,我建议阅读关于live的文档,因为live早就被弃用了。此外,看到mouseenter和mouseleave可能会很有趣。想法与live相同。

您可以查看jquery的.live函数。这里是链接

您可以查看jquery的.live功能。这里是链接

最好使用委托而不是live,因为live本质上是document.body上的委托,这会导致它冒泡的时间更长


下面是一个使用委托的示例:

最好使用委托而不是live,因为live本质上是document.body上的委托,这会导致它冒泡的时间更长


下面是一个使用委托的示例:

首先,谢谢,我刚刚尝试了您的示例。很好,我将在文档中查找详细信息。您的代码只执行else块中的指令,因此我用mouseover更改了mouseenter,现在它工作得很好。首先,谢谢,我刚刚试过你的例子,很好,我会在文档中查找详细信息。你的代码只执行else块中的指令,所以我用mouseover修改了mouseenter,现在它工作得很好。