jQuery .on()不适用于克隆的元素 [英] jquery .on() doesn't work for cloned element

查看:114
本文介绍了jQuery .on()不适用于克隆的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎.on()未能绑定clone()

<div class="container">
<div class="add">add</div>
</div>


$(".remove").on("click",function() {
    $(this).remove();
});

$(".add").on("click", function() {
 $(this).clone().toggleClass("add remove").text("remove").appendTo($(".container"));
});

jsfiddle

为什么这不起作用?

更新: 请注意,我知道.clone()具有两个参数,但是我不想让克隆的元素继续注册到旧事件,但是我可以使用.off().on()再次注册到旧事件,但是我的问题是为什么以前声明的.on(".remvove")没有捕获克隆元素中的更改.

Update: please note that, I know .clone() takes two parameters, but I don't want to let the cloned element continue registered to the old events, but a new one, I could use .off() and .on() to register again, but my question is why the previously declared .on(".remvove") didn't capture the change in the cloned element.

推荐答案

因为您需要将布尔参数传递给clone,以便将所有数据和事件处理程序附加到克隆的元素上.

Because you need to pass a boolean parameter to clone so that all data and event handlers will be attached to cloned element.

https://api.jquery.com/clone/

$(".remove").on("click",function() {
    $(this).remove();
});

$(".add").on("click", function() {
 $(this).clone(true).toggleClass("add remove").text("remove").appendTo($(".container"));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="add">add</div>
</div>

已编辑

$(".container").on("click", '.remove', function() {
    $(this).remove();
});

$(".add").on("click", function() {
 $(this).clone().toggleClass("add remove").text("remove").appendTo($(".container"));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="add">add</div>
</div>

这篇关于jQuery .on()不适用于克隆的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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