The basic difference between the two is who you link the event to click
.
In the first case it will capture the event when it arrives at the body
and originate from the desired selector. As javascript events propagate, when the user clicks on the selector it will propagate to the body
and you will capture correctly.
In the second you attach the event directly to the selector. When the click originates in it, you will capture the event.
And what is the advantage of linking to body
? When you do this, it is not necessary for the element to exist on the page. This is extremely useful when you create the element dynamically. You can tie the event to it without necessarily creating the element yet.
$('body').on('click', '#botao', carregaItems);
var botao = $('<div id="botao">ola</div>');
$('body').append(botao);
The click
on the button will trigger the function carregaItems
In the second case, you depend on the element to be present on the page to link the event to it. If the code that links the event is executed before the code that creates the element, the element is left unheard in the event.
$('#botao').click(carregaItems);
var botao = $('<div id="botao">ola</div>');
$('body').append(botao);
The click
on the button nay will trigger the function carregaItems
why is the bind
event in an element that does not exist in the DOM
yet.
Related: http://answall.com/questions/5196/qual-a-diferen%C3%A7a-entre-o-onclick-Function-e-o-clickfunction
– Jeferson Almeida