2012-06-04 39 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"); });