.click () does not work after changing dom

I searched on the Internet, but I did not find the answer, since this “problem” is not common for the difference between .on () and .click (). As of jQuery 2.1.3, the click function is shortand for on.("click", handler) , so it should run the function (or wathever) after changing the dom. But this only works if I use .on (). What for? (Example below)

 $('#button1').click(function() { $('div').html("<p id="button2">Hello</p>"); }); $('#button2').click(function() { alert(0); //THIS DOESN'T WORK }); $(body).on("click", "#button2", function() { alert(0); //THIS WORKS! }); 
+5
source share
3 answers

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.

+2
source

Answer: if you added data dynamically, you should use the .on function. With this code, you can use the concept of event delegation using the code you mention at last. Since the DOM is not yet registered, the .click handler cannot capture a new DOM element.

+2
source
 $('#button1').click(function() { $('div').html("<p id='button2'>Hello</p>"); }); $('#button2').click(function() { alert(0); //THIS DOESN'T WORK }); $(document).on("click", "#button2", function() { alert(0); //THIS WORKS! }); 

This is the correct code.

https://jsfiddle.net/hhe3npux/

+1
source

All Articles