This is basically how the association for the element is made. .click
applies to the current DOM, while .on
(using delegation) will continue to be valid for new elements added to the DOM after event association.
Which is better to use, I would say it depends on the case.
Example:
<ul id="afazer">
<li>Afazer 1</li>
<li>Afazer 2</li>
<li>Afazer 3</li>
<li>Afazer 4</li>
</ul>
Event .click
:
$("#afazer li").click(function() {
$(this).remove();
});
Event .on
:
$("#afazer").on("click", "li", function() {
$(this).remove();
});
Note that I've separated the selector in .on
. I'll explain why.
Suppose that after this association, let's do the following:
$("#afazer").append("<li>Afazer 5</li>");
That's where you'll notice the difference.
If the event was associated with .click
, job 5 will not obey the click event, and thus will not be removed.
If it was associated via .on
, with the separate selector , it will obey.
Credits