2010-11-08 81 views
1

後創建的元素:如果我把這個jQuery並不適用於頁面加載

$(".month-selector").change(function(){ 
    setStones(); 
}); 

$(document).ready()裏面它並不適用於以後創建的元素。我也嘗試在創建它們之後調用上面的代碼,如下所示:

$("#month-selectors").html(month_selectors); 

$(".month-selector").change(function(){ 
    setStones(); 
}); 

它仍然不起作用。但是,如果我創建一個靜態的,它的工作。

如何在頁面加載後創建它們時將此應用於元素?

+0

附註...您不需要'function(){setStones(); }',你可以通過'setStones'函數作爲事件處理函數:'$(「。month-selector」)。change(setStones)' – gnarf 2010-11-08 20:55:18

+0

@gnarf,謝謝!我知道這一點,但我原本以爲我會需要參數,然後沒有,所以我忽略了這一點。感謝您指出了這一點! :) – 2010-11-08 20:59:01

回答

14

您可以使用jQuery的'live()'方法將事件偵聽器添加到當前和未來的節點。

$(".month-selector").live('change', function(){ 
    setStones(); 
}); 
+0

這是我正在尋找的解決方案。當分配時間結束時,我會在12分鐘內標記出您的正確答案。 – 2010-11-08 20:53:25

+0

這隻適用於jQuery版本1.3+ – RedWolves 2010-11-08 20:54:02

+0

實時方法的缺點是什麼?我猜一些額外的開銷,因爲jquery必須觀看DOM才能出現新節點? – CodexArcanum 2010-11-08 20:55:46

0

嘗試:

$(".month-selector").live("change", function(event) { 
// some code 
}); 
2

這是超級有幫助!但是,如果您在DOM已加載後添加輸入事件,則需要使用「單擊」事件才能使其工作:

$("input#thename").live("click", function(event) { 
// handler for what should happen when somebody clicks on the new input field, in this case I needed a datepicker to pop up so lets get that fired. Now that the click element registered the new input object with the DOM, it can be used like a normal jQuery selector! 
    $("input#thename").datepicker(); 
    }); 
+0

但由於某種原因。我必須在輸入框上點擊兩次才能讓日期選擇器顯示...有關如何解決的任何想法? – 2011-07-04 20:00:59

相關問題