2013-07-26 36 views
1

使用任何事件,例如在元件上mouseenterclick不會與負載有infinitescrolljquery.load,或jquery.ajax元件工作。事件不工作的加載元件

我不明白爲什麼。我明白函數需要被調用,但是點擊事件仍然可以工作,因爲加載的元素具有相同的類和類,但它們不會!

不僅事件不能正常工作,而且如果我在新元素加載後記得它,已加載的元素現在累積了兩個事件,因此如果您執行類似$('.class').toggleClass('.anotherclass')的操作,它將添加並刪除類,因爲現在有兩個事件,而不僅僅是一個事件。

爲什麼會發生這種情況?我怎麼能有一個不會像那樣積累的事件?

希望我很清楚,謝謝!

+0

有些人稱之爲「代表團」,我把它稱爲相同的......;)將事件委託給最接近的靜態元素。檢查jquery .on()文檔:http://api.jquery.com/on/#direct-and-delegated-events –

回答

1

我已經在在動態創建一個需要綁定到這些事件偵聽器的元素在過去的這個問題,這是你需要做的:

$(document).on("event", "#selector", function(){ 
    //Your code here 
}); 

綁定到該文件將允許所有動態事件被正確觸發。只需將事件更改爲您所需的選項以及您需要的選擇器,它就可以工作。

+0

美麗!謝謝:) –

+0

@RyanSaxe很高興幫助! – defaultNINJA

0

這實際上取決於你如何附加事件處理程序。例如:

// This will be attached to all currently existing elements with class 
// .class, but not to future ones 
$('.class').click(handler); 

使用on()

// This is attached to the document and if the target of the event 
// matches the provided selector then the event would be triggered 
// on it. Here it doesn't matter whether the element with class 
// .class existed at the time the handler was attached 
$(document).on('click', '.class', handler); 

我的回答多半是評論裏面,但基本上不同的是在事件處理程序是直接或委託。