各种ajax 方法接受一个回调,您可以在其中将处理程序绑定到新元素。
您还可以将事件委托与delegate()[docs] 方法或live()[docs] 方法一起使用。
事件委托的概念是您不将处理程序绑定到元素本身,而是绑定到页面加载时存在的某个父容器。
事件从容器内的元素冒泡,当它到达容器时,会运行一个选择器来查看接收到事件的元素是否应该调用处理程序。
例如:
<div id="some_container"> <!-- this is present when the page loads -->
<a class="link">some button</a> <!-- this is present when the page loads -->
<a class="link">some button</a> <!-- this is present when the page loads -->
<a class="link">some button</a> <!-- this is present when the page loads -->
<a class="link">some button</a> <!-- this one is dynamic -->
<a class="link">some button</a> <!-- this one is dynamic -->
<a class="link">some button</a> <!-- this one is dynamic -->
<span>some text</span> <!-- this one won't match the selector -->
<span>some text</span> <!-- this one won't match the selector -->
</div>
现场示例: http://jsfiddle.net/5jKzB/
因此,您将处理程序绑定到some_container,并将一个选择器传递给.delegate(),在这种情况下查找"a.link"。
当在some_container 中单击与该选择器匹配的元素时,将调用处理程序。
$('#some_container').delegate('a.link', 'click', function() {
// runs your code when an "a.link" inside of "some_container" is clicked
});
所以你可以看到,"a.link" 元素何时添加到 DOM 中并不重要,只要在页面加载时 some_container 存在即可。
live()[docs]方法同理,只不过容器是document,所以它处理所有页面上的点击。
$('a.link').live('click',function() {
// runs your code when any "a.link" is clicked
});