hi, i have a code that bind's on click action on page load, it is a link. When i clicking it, it send ajax request and replace content in some div with jquery append() function. This new content has a links and i need to bind some action for them, but i could't.. bind did't work i think, because jquery append doesn't update DOM tree. How could i get a late binding?
+6
A:
Late binding is now available by utilizing jQuery's live() event:
$('a.my-links-class').live('click', function() {
// do your link action here
});
cballou
2009-12-14 18:48:39
This just made my day. live() is amazing!
AnApprentice
2010-03-02 03:53:37
+1
A:
You can use jQuery 1.3+'s $().live(event, function)
function. $("a").live("click", myClickFunc)
will bind myClickFunc
just like $("a").click(myClickFunc)
or $("a").bind("click", myClickFunc)
, but the events will be bound "live", so elements that are added to the DOM after that function call will also be bound.
You can remove live-bound events with $().die()
.
For more information on $().live, see the documentation for it.
Another option would be to have a function to bind the elements given a certain context (using the $ selector function's rarely-used second parameter):
function myBindEvents(context) {
$("a", context).click(myClickFunc);
}
and call that whenever you update an element with AJAX:
$("<div>").load("...", "...", function(){myBindEvents(this);});
Hope this helps. :)
AKX
2009-12-14 18:52:40