The basic difference between the two is where you tie the click
event.
In the first case it will capture the event when it arrives at body
and has origin in the desired selector. As events in javascript propagate, when the user clicks the selector it will propagate up to body
and you will capture correctly.
In the second you link the event directly to the selector. When the click originates from it, you will capture the event.
And what is the advantage of linking body
? When you do this, there is no need for the element to exist on the page. This is extremely useful when you create the element dynamically. You can bind the event to it without necessarily having created the element yet.
$('body').on('click', '#botao', carregaItems);
var botao = $('<div id="botao">ola</div>');
$('body').append(botao);
The click
on the button will fire the function carregaItems
In the second case, you rely on the element to be present on the page to bind the event to it. If the code that runs the event runs before the code that creates the element, the element goes unheard in the event.
$('#botao').click(carregaItems);
var botao = $('<div id="botao">ola</div>');
$('body').append(botao);
The% wont of the button will not trigger the click
function because the carregaItems
of the event is made on an element that does not exist in bind
yet.