Reputation: 2312
I change some methods from $(selector).live('click', function(){});
to $(selector).on('click', function(){});
.
At first it seems to work exactly the same. But when I insert new html on the DOM, the new elements inserted with the same selector, they aren't catch by $(selector).on('click', function(){});
and before they were catch by the live() method.
why? I'm missing something?
Upvotes: 1
Views: 147
Reputation: 227310
.on
takes a different set of parameters compared to .live
. You can't just replace one with the other (and .$(selector).on.live
doesn't make sense)
The correct syntax is:
$(document).on('click', selector, function(){});
This will bind to all elements that match selector
no matter when they are added to the DOM.
Note:
Instead of document
, you can use a parent of the element(s), as long as that parent stays in the DOM.
For example:
<div id="myDiv">
<p>Hello World</p>
<p>Hello World</p>
</div>
Then you can do:
$('#myDiv').on('click', 'p', function(){});
That click event will fire for all <p>
tags added to #myDiv
.
Note:
$(selector).on('click', function(){})
is the same as doing
$(selector).bind('click', function(){})
(jQuery 1.7.1 suggests using .on
instead of .bind
)
Upvotes: 4