.dom更改后.click()失败 [英] .click() fails after dom change

查看:87
本文介绍了.dom更改后.click()失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上搜索,但没有找到任何答案,因为这个问题"不是关于.on()和.click()之间区别的常见问题. 在jquery 2.1.3中,click函数是on.("click", handler)的缩写,因此在更改dom后应该触发一个函数(或重要函数). 但这仅在我使用.on()时有效. 为什么? (下面的示例)

I searched on web but I didn't find any answer since this "problem" is not the usual one about the difference between .on() and .click(). With jquery 2.1.3 the click function is a shortand for on.("click", handler) so it should fire a function (or wathever) after the dom is changed. But this works only if I use .on(). Why? (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!
});

推荐答案

但这仅在我使用.on()时有效.

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

首先,您应该意识到:

如果

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

之后

$('#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); 
      });
    });

然后它将起作用.

您在上一个代码中所做的事情是将处理程序附加到由于事件传播而起作用的body元素上.

the thing which you did in the last code is attaching the handler to the body element which is working because of event propagation.

您的代码有效,因为on允许您进行选择器匹配,并将单个处理程序附加到body元素上.

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

这篇关于.dom更改后.click()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆