2011-07-13 52 views
1

首先这是我在jQuery代码中的一个例子,我在一个函数中用来做分页:jQuery:在设置HTML内容后立即附加事件

// 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 
}); 

但是悬停事件根本不起作用,我相信这是因为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我希望有人告诉我正确的方法。

回答

0

最好使用一个委托而不是实况,因为live实质上是document.body的一个委托,导致它必须冒泡很长时间。

下面是使用委托的示例:http://jsfiddle.net/Akkuma/wLDpT/

+0

先谢谢,我只是试过你的例子,这很好,我会在文档中查看细节。 – Hidalgo

+0

你的代码只执行else块中的指令,所以我通过mouseover改变了mouseenter,现在它完美地工作。 – Hidalgo

2

你会想使用实时mouseovermouseleave事件

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

UPDATE

在jQuery中的新版本,你可以不喜欢它这

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

您是对的,谢谢。 – Hidalgo

+0

欢迎您 – brenjt

2

也许您需要使用live()方法。正如你可以阅读here,似乎你需要将两个事件分开:

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

UPDATE:有人投了我,所以如果有人送过来,我推荐阅读on()文档(here)因为live很久以前就被弃用了。此外,看到mouseenter()link)和mouseleave()link)可能会很有趣。这个想法与live相同。

相关问题