2011-07-13 48 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相同。

相關問題