jQuery事件多次触发
我的divs克隆了,其中包含将父母克隆的按钮。尝试单击按钮后,事件被触发2n
次,以便单击第二个克隆会产生其他4个克隆,依此类推:
$(".add").off("click").on("click", function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
$(".cloneable").clone(true).appendTo(".container");
});
$(".rem").off("click").on("click", function() {
if (document.getElementsByClassName('container')[0].childElementCount > 1) {
$(".cloneable:last").remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="cloneable">
<div>
<a class="btn btn-primary add" role="button">Add cell</a>
<a class="btn btn-primary rem" role="button">Remove cell</a>
</div>
<iframe src="index.php"></iframe>
</div>
</div>
What could I be doing wrong?I have cloned divs containing buttons that clone their parents. Upon trying to click the buttons, events are triggered 2n
times such that clicking the second clone produces 4 other clones and so on:
$(".add").off("click").on("click", function(e) {
e.stopPropagation();
e.stopImmediatePropagation();
$(".cloneable").clone(true).appendTo(".container");
});
$(".rem").off("click").on("click", function() {
if (document.getElementsByClassName('container')[0].childElementCount > 1) {
$(".cloneable:last").remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="cloneable">
<div>
<a class="btn btn-primary add" role="button">Add cell</a>
<a class="btn btn-primary rem" role="button">Remove cell</a>
</div>
<iframe src="index.php"></iframe>
</div>
</div>
What could I be doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
几件事。
first
。 jQuery会找到所有可克隆
,而不仅仅是您的原始内容。禁用的
类将被添加/删除到rem
按钮,具体取决于是否仅剩下一个。A few things.
first
. jQuery will find allcloneable
and clone them, not just your original.disabled
class will be added/removed to therem
button, depending on if there is only one left or not.因此,方法中正在发生的事情是,您每次单击时都在进行新的查询,并且它返回所有
.clonable
elements,然后再克隆。您想要的只是找到与您单击的项目相关的一个,因此您要以$(this)
开始,这是单击的项目,然后您可以使用parent( )
沿着DOM树寻找选择器的方法。在这种情况下,可以在单击事件中放置
调试器;
,然后一次执行方法。像$('。clonable')
。然后,您可以看到它每次都会变得更大,并且它们指出了所有现有元素。So, what's happening in your method is that you are doing a new query each time you click and it returns all the
.clonable
elements and then clones them. What you want is to only find the one relevant to the item you clicked on, so you want to start with$(this)
which is the item clicked and then you can use theparent()
method to go up the DOM tree looking for the selector.In these sorts of situations, it can help to put a
debugger;
inside your click event and then execute the method one at a time. Like$('.clonable')
. You can then see maybe that it gets larger every time and that they point to all the existing elements.