My HTML
<div>
<span class="more-available" data-completeMessage="This is the complete message you see after clicking more">Hello</span>
</div>
I add a anchor tag to the end dynamically and then want to attach a click handler to the anchor tag. So I do this
$(document).ready(function() {
//Attach future proof click event to an anchor tag
$('a.more').on('click', function() {
var $parent = $(this).parent();
$parent.text($parent.data('completemessage'));
});
//Add the anchor tag
$('span.more-available').append($('<a class="more">...more</a>'));
});;
This does not work. If i replace “on” by “live” it works. (but live is depreciated)
I know I can do this
$(document).ready(function() {
$('div').on('click','a.more', function() {
var $parent = $(this).parent();
$parent.text($parent.data('completemessage'));
});
$('span.more-available').append($('<a class="more">...more</a>'));
});;
and it works, but my question is…
Was I wrong in assuming that “on” provides all the functionality of live? Does “on” not bind to future elements? Is this correct behavior, or am I doing something wrong.
on()is just a binder that allows for target delegation. It’s more of a replacement fordelegate()than forlive().$('foo').live('click',fn);is essentially$(document).on('click','foo',fn);With that in mind, you simply bind the click event to the constant parent wrapper and delegate to your target, like so: