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"));
});
为什么这不起作用?
更新:
请注意,我知道.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.
$(".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>