jquery binding events to dynamically loaded html elements

旧街凉风 提交于 2019-11-28 00:13:32

The various ajax methods accept a callback where you can bind the handlers to the new elements.

You can also use event delegation with the delegate()[docs] method or the live()[docs] method.

The concept of event delegation is that you do not bind the handler to the element itself, but rather to some parent container that exists when the page loads.

The events bubble up from the elements inside the container, and when it reaches the container, a selector is run to see if the element that received the event should invoke the handler.

For example:

<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>

Live Example: http://jsfiddle.net/5jKzB/

So you bind a handler to some_container, and pass a selector to .delegate() that looks for "a.link" in this case.

When an element that matches that selector is clicked inside of some_container, the handler is invoked.

$('#some_container').delegate('a.link', 'click', function() {
    // runs your code when an "a.link" inside of "some_container" is clicked
});

So you can see that it doesn't matter when the "a.link" elements are added to the DOM, as long as the some_container existed when the page loaded.

The live()[docs] method is the same, except that the container is the document, so it processes all clicks on the page.

$('a.link').live('click',function() {
    // runs your code when any "a.link" is clicked
});

Then you'll want to use .live(). Have a look at http://api.jquery.com/live/.

Example:

$('a').live('click', function() {
  // Do something useful on click.
});

In the example above, any A elements, whether already existing or loaded after the document is loaded, will trigger the click event.

These answers are now obsolete since the .live() method has been deprecated since version 1.7 of jQuery. For jQuery 1.7+ you can attach an event handler to a parent element using .on()

bind them using .live(). It will attach the event handler to any element that matches the selector even if it doesn't exist on the page yet.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!