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

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

问题描述

似乎 .on() 未能从 clone()

绑定新创建的元素

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

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

jsfiddle

为什么这不起作用?

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

解决方案

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

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

$(".remove").on("click",function() {$(this).remove();});$(".add").on("点击", 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="容器"><div class="add">add</div>

已编辑

$(".container").on("click", '.remove', function() {$(this).remove();});$(".add").on("点击", 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="容器"><div class="add">add</div>

It seems .on() failed to bind newly created element from 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

Why this doesn't work?

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.

解决方案

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>

Edited

$(".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天全站免登陆