views:

299

answers:

4

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?

+2  A: 

You need to use jQuery's live function, which will bind an event to all elements that match a selector, no matter when they were created.

SLaks
+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
This just made my day. live() is amazing!
AnApprentice
+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
A: 

Thank's a lot guys, now all working fine!

teMkaa