开发者

Applying jQuery event handlers to AJAX content [duplicate]

This question already has answers here: 开发者_如何学编程 Event binding on dynamically created elements? (23 answers) Closed 8 years ago.

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:

  1. put my .click() handler assignments within a JScript function, and call it every time content is refreshed via AJAX.
  2. 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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜