Reputation: 51
I hava a simple jQuery script. I use .ajax() to get some info from my database, it works perfect.
The problem is the php-code genereate xhtml code with a-tags with different class, like .info, .delete and .edit.
I want to do stuff when i click in my .info link. I have tried this code:
$('a.info').click(function (e) {
e.preventDefault();
alert('Do stuff');
});
it dosen't work at all, nothin happens. firebug gives me no error so i dont know how to solve the problem.
$('a').click(function (e) {
e.preventDefault();
alert('Do Stuff 2');
});
works on all links on the site but not on the link that is generated from the php code.
my code:
$(function(){
$.ajax({
type: "POST",
url: 'users.php',
data: 'getall=true',
success: function( r ) {
$(' #content ').html( r );
},
error: function( ) {
alert('Error');
}
});
$('a.info').click(function (e) {
e.preventDefault();
alert('Do Stuff');
});
$('a').click(function (e) {
e.preventDefault();
alert('Do Stuff 2');
});
});
Upvotes: 0
Views: 4926
Reputation: 9382
Use $.live. $.click registers the click events on objects that are currently present. Using $.live means your click events are basically re-registered when new elements are added to the page.
Upvotes: 1
Reputation: 15961
It looks like you're getting the HTML from the AJAX request. The click function will set up handlers for the objects that it knows about at the time you call - in this case, it is after the DOM is loaded but before the AJAX request is returned.
To handle the click event for any object that is added after the DOM is loaded, use the live
function:
$('a.info').live('click', function (e) {
e.preventDefault();
alert('Do stuff');
});
Upvotes: 0