.click() fails after dom change

情到浓时终转凉″ 提交于 2019-11-29 14:04:31

But this works only if I use .on().

First of all , you should realize that :

If

$('#button2').click(function() {
    alert(0); 
});

comes 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 which you did in the last code is attaching the handler to the body element which is working because of event propagation.

your code is working beacuse on allows you to do selector matching + attaching single handler to the body element.

$('#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 correct code

https://jsfiddle.net/hhe3npux/

The answer is if you added data dynamically, then you must use .on function. With this code, you can use event delegation concept by using the code that you mention at last. Since the DOM are not registered yet, the .click handler cant capture the new DOM element.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!