But this only works if I use .on ().
First of all, you should understand that:
If
$('#button2').click(function() { alert(0); });
appears after
$('#button1').click(function() { $('div').html("<p id="button2">Hello</p>"); });
like:
$('#button1').click(function() { $('div').html("<p id="button2">Hello</p>"); $('#button2').click(function() { alert(0); }); });
Then it will work.
the thing you did in the last code binds the handler to the body element, which works due to the propagation of the event.
your code works beacuse on allows you to do a selector match + attach a separate handler to the body element.
source share