Reputation: 97
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?
Upvotes: 3
Views: 1907
Reputation: 126052
click()
only will work on elements that exist on the page currently. Check out live
and delegate
. With live
:
$('a.selected_class').live("click", function(e){
alert('alert');
e.preventDefault();
});
As patrick dw mentions, delegate
is preferred if possible.
Upvotes: 6
Reputation: 322502
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.
Upvotes: 3