jquery绑定事件到动态加载的html元素

ahh*_*hek 6 jquery events document ready

使用jquery,我们可以将事件处理程序附加到页面中的元素,这是在document.ready()函数中完成的.现在我的困难是我在下载文件后有一些元素,比如稍后加载链接等(使用ajax请求).因此,这些新元素无法与我在页面中定义的处理程序绑定.有没有办法知道什么时候跟着ajax查询完成,然后在里面我可以绑定我的事件处理程序.

提前致谢

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)

  • .live()自1.7以来已被弃用,并在1.9中被删除,因此请确保您现在使用.on()! (2认同)

Jas*_*zek 0

使用.live()绑定它们。它将事件处理程序附加到与选择器匹配的任何元素,即使页面上尚不存在该元素。