It is basically how the association to the element is made. .click
applies to the current FOD, while the .on
(using delegation) will continue to be valid for new elements added to the DOM after the event’s association.
Which is better to use, I would say 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 separated the dial on .on
. Now I’ll explain why.
Suppose after this association, we do the following:
$("#afazer").append("<li>Afazer 5</li>");
That’s where you’ll notice the difference.
If the event was associated via .click
, afazer 5 will not obey the click event, and so will not be removed.
If you were associated via .on
, with the separate selector, he will obey.
Credits
It is important to choose the selector "father" to which the event will be delegated being the "closest ancestor" possible. In other words: it is better to avoid carrying everything on the back of the
document
, which is the common ancestor of all elements.– J. Bruni
For example: if you want to capture the click on cells in a table, which may appear/disappear dynamically, instead of
$(document).on('click', 'td')
it is preferable to use$('table').on('click', 'td')
- the idea is to use the element selector that captures the event, which is as close as possible to the one that will delegate the event.– J. Bruni