2012-06-04 47 views
2

從文檔更換現場()與()

$(selector).live(events, data, handler);    // jQuery 1.3+ 
$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+ 
$(document).on(events, selector, data, handler);  // jQuery 1.7+ 

我使用jQuery 1.7.1

這工作,爲靜態元素和動態加載的元素:

$("input").live("change", function() { alert("hello"); }); 

這不起作用,甚至不適用於靜態元素:

$("document").on("change", "input", function() { alert("hello"); }); 

我錯過了什麼?

回答

8

寫它像

$(document).on("change", "input", function() { alert("hello"); }); 

您可以將始終存在DOM有更好的表現任何closer parent element更換document。像

$('#closest_static_container_id').on("change", "input", function() { 
    alert("hello"); 
}); 
如果使用 $("document") jQuery將尋找一個名爲 document<document> node/tag並不會發現任何東西作爲 document實際上是一個 object

但是你可以使用$("body")作爲bodyDOM的節點/元素。

+0

呃,這麼愚蠢的錯誤。我想這是漫長的一天。 – Stijn

4

變化:

$("document").on(...) 

到:

$(document).on("change", "input", function() { alert("hello"); }); 

document是一個對象(的window一個屬性),而不是一個節點類型。

$("document").on(...) 

document對象尋找<document>元素,如:

<document> 

正如你可能已經得到了,有沒有...

反正與on的最佳實踐是使用動態添加的元素的最接近的靜態元素類似於:

<div id='container-div-id'> 
    <input /> ... this will be added later. 
</div> 

$('#container-div-id').on("change", "input", function() { 
    alert("hello"); 
}); 
2

document是一個對象,您將它用作字符串。所以jQuery會嘗試使用它作爲一個css選擇器,它不會找到任何東西來附加事件處理程序。

試試這個。

$(document).on("change", "input", function() { alert("hello"); });