I was using the live()
function:
$('a.remove_item').live('click',function(e) {});
I needed to change this to one()
to prevent multiple clicks, however when I inject one of these elements after the page has loaded the one()
listener does not fire.
How can I get one()
to behave like live()
?
Use the on() method instead. The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur. Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).
In short: . bind() will only apply to the items you currently have selected in your jQuery object. . live() will apply to all current matching elements, as well as any you might add in the future. The underlying difference between them is that live() makes use of event bubbling.
on() method: This method attaches events not only to existing elements but also for the ones appended in the future as well. The difference here between on() and live() function is that on() method is still supported and uses a different syntax pattern, unlike the above two methods.
Try this:
$('a.remove_item').live('click',function(e) {
if($(e.target).data('oneclicked')!='yes')
{
//Your code
}
$(e.target).data('oneclicked','yes');
});
This executes your code, but it also sets a flag 'oneclicked' as yes, so that it will not activate again. Basically just sets a setting to stop it from activating once it's been clicked once.
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