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
});