问题描述
限时送ChatGPT账号..似乎 .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/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/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/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/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/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/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
<div class="add">add</div>
</div>
这篇关于jquery .on() 不适用于克隆元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论