Applying jQuery event handlers to AJAX content [duplicate]
I'm sure this is something that AJAX gurus learn very early on, but this is the first time I've run into it. Using jQuery, I have assigned .click() handlers to certain CSS classes. However, if I reload some of the content via AJAX, the .click() handlers are not firing for that content.
It seems I have two choices:
- put my .click() handler assignments within a JScript function, and call it every time content is refreshed via AJAX.
- use onclick="" rather than jQuery within my AJAX content.
So far, it seems #1 would be the best; it's more consistent and yields smaller HTML for AJAX.
Is there another way to do it? Perhaps a different way of assigning the .click() handlers from the outset?
You are looking for the live()
method instead.
$('selector').live('click', function(){
// your code.......
});
The live
works for elements present now or in the future.
If you are using jQuery 1.4+, .live() is part of the core. If not then there is a plugin called livequery that provides the functionality you are looking for.
Check out the bind or live methods, check this out: http://api.jquery.com/live/
精彩评论