use*_*716 22
各种ajax方法接受回调,您可以将处理程序绑定到新元素.
您还可以使用事件代表团与delegate()[文档]法或live()[文档]方法.
事件委托的概念是您不将处理程序绑定到元素本身,而是绑定到页面加载时存在的某个父容器.
事件从容器内的元素冒泡,当它到达容器时,运行选择器以查看接收事件的元素是否应该调用处理程序.
例如:
<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>
Run Code Online (Sandbox Code Playgroud)
实例: 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
});
Run Code Online (Sandbox Code Playgroud)
因此,您可以看到,将"a.link"元素添加到DOM 时无关紧要,只要some_container页面加载时存在即可.
的live()[文档]方法是相同的,不同之处在于容器是document,因此它处理所有页面上点击.
$('a.link').live('click',function() {
// runs your code when any "a.link" is clicked
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29730 次 |
| 最近记录: |