Reputation: 24112
I have known for a while now that .on is supposed to replace .live, however I have never been able to get it to work at all.
I have tried:
$(this).on('click', function(){
// Do something...
})
$(this).on({
click: function(){ // Do something }
})
But it never works for me!
Specifically when I'm trying to bind events to elements that may not exist on the page initially.
Could someone please clear this up for me once and for all?
I'm using the latest version of jquery.
Upvotes: 2
Views: 74
Reputation: 3118
For dynamically generated elements you need to use like
$(document).on('click','YOUR SELECTOR', function(){
});
It's because document is the container of your elements which can watch changes to the DOM. For every action, there needs to be an explicit event listener. If you bind something to $(this), it (the selector) might not exist when you remove it.
Upvotes: 2
Reputation: 5291
Do it like:
$(".parent").on('click', ".child", function(){
// Do something...
})
The syntax you are using works just like bind
. To bind event to all future elements, use above syntax.
Upvotes: 2
Reputation: 198324
You need to specify which elements.
$element.on('click', '.foo', handler)
will bind handler
to all live .foo
inside $element
.
Upvotes: 1