Jquery selector stops working after loading ()

In short, I have a page where the content is loaded using jquery load (). The problem is when I try to choose.

$('a.selected_class').click(function(e){
 alert('alert');
 e.preventDefault();
});

(inside the document is ready) it works on the first page, but on any subsequent pages (which are loaded using $ (this) .load (url); in the div) the selector stops working.

any advice?

+3
source share
2 answers

This does not mean that it stops working. The fact is that it binds handlers clickonly to those elements that exist at startup (when the page loads).

You can put a .delegate()handler on <div>which dynamic ones are loaded.

$('#mydiv').delegate('a.selected_class','click',function(e){
   alert('alert');
   e.preventDefault();
});

#mydiv, click , , , a.selected_class.

.live() , , .

+3

click() , . live delegate. live:

$('a.selected_class').live("click", function(e){
 alert('alert');
 e.preventDefault();
});

patrick dw, delegate , .

+6

Source: https://habr.com/ru/post/1784448/


All Articles