2012-02-28 61 views
0

例如,爲什麼我會使用一些虛擬代碼。jQuery添加html與特定類的jQuery動作沒有任何影響

我有些jQuery的設置發送出去Ajax請求,並使用具有一類「activate_tooltip」

初始的jQuery一個div替換特定div的HTML被送出使用

$('.button').live('click', function() { 

    //Ajax request goes out 
    //Div gets replaced with content like so 
    //$('.response_div').html('<div class="activate_tooltip"></div>'); 

}); 

我有一個用於測試目的的.activate_tooltip類的偵聽器設置,應該在發生懸停時向窗口發送警報。我使用firebug來驗證div內容是否被添加到dom中(並且.activate_tooltip類在新添加的div中拼寫正確)...但是懸停在新添加的div上卻什麼也不做。但是,頁面上已存在的div在懸停時會激活警報。

任何想法?

回答

1

既然你要添加的div動態,你應該使用delegateon(jQuery的版本1.7+)事件對動態元素的工作。嘗試這個。

使用delegate

$('.response_div').delegate('.activate_tooltip', 'mouseover', function() { 
    alert('Hovered'); 
}); 

使用on

$('.response_div').on('mouseover', '.activate_tooltip', function() { 
    alert('Hovered'); 
}); 

如果您對mouseovermouseout事件相同的行爲,那麼你可以使用hover事件,而不是mouseover

參考文獻: