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:
$(document).ready(function(){
$('body').on('click','button', function() {
alert('Clicked.');
// ...AJAX request...
});
});
In this way is the body
element that handles all the click
event 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 used on()
, jQuery just intercept events when they bubble up the DOM
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With