Let’s say, for example, that I have some buttons that calls AJAX requests when clicked.
$(document).ready(function(){
$('button').each( function() {
$(this).click( function() {
alert('Clicked.');
// ...AJAX request...
});
});
});
When I click on a button, everything works fine.
But if I load the buttons with an AJAX request and then I click on them, the code above stops working.
How can I get rid of this?
I have tried the on() method
$(document).ready(function(){
$('button').each( function() {
$(this).on('click', function() {
alert('Clicked.');
// ...AJAX request...
});
});
});
But it’s just the same. Works normally, doesn’t work on AJAX-loaded content.
I’m stuck, please help me.
P.S.: I am using the latest version of jQuery (v1.7.1).
You should do:
In this way is the
bodyelement that handles all theclickevent on the<button>elements and it works even if they are added through AJAX.Instead of using the
<body>tag you could use something that wraps those<button>…in any case read the docs of jQuery for on(), it’s pretty straightforward.P.S. in case you are wondering,
live()works exactly as i usedon(), jQuery just intercept events when they bubble up the DOM