Search code examples
jqueryjquery-selectorscss-selectorsjquery-load

jquery selector stops working after load()


in short, i have a page where the content is being loaded with jquery load(). the problem is when i am trying to select.

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

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

any tips?


Solution

  • It isn't that it stops working. It is that it only binds click handlers to those elements that exist when it runs (on page load).

    You can place a .delegate() handler on the <div> that the dynamic ones are loaded into.

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

    The handler is placed on the #mydiv element, and when the click event bubbles up to it, it tests to see if the event took place on an element that matches a.selected_class.

    The .live() method does the same thing, but it does it for the entire document, so it normally isn't an advisable method to use.