[英]How to unbind events of dynamic elements?
I use the following to bind click
event on certain elements that are inserted into DOM on the fly.我使用以下内容在动态插入到 DOM 的某些元素上绑定
click
事件。
jQuery('#cont').on('click', '.myElement1', ....);
In this case, how would I unbind
them?在这种情况下,我将如何解
unbind
它们?
For what it's worth, jQuery('.myElement1').unbind('click')
isn't working, as in the code inside the click event is executing multiple times because the click
events are being registered multiple times.就其价值而言,
jQuery('.myElement1').unbind('click')
不起作用,因为单击事件内部的代码正在执行多次,因为click
事件被多次注册。
You cannot unbind the event handler on .myElement1
as it was bound to #cont
.您无法取消绑定
.myElement1
上的事件处理程序,因为它已绑定到#cont
。 There's no way to remove the event from that single .myElement1
instance without affecting all the other ones.无法在不影响所有其他实例的情况下从单个
.myElement1
实例中删除事件。
What you could do as a workaround is to add another class to the .myElement
and then exclude that class from the dynamic selector:您可以做的解决方法是向
.myElement
添加另一个类,然后从动态选择器中排除该类:
$('#cont').on('click', '.myElement1:not(.ignore)', function() { console.log('Foo clicked'); }); $('.add').click(function() { var $div = $('<div>Foo</div>').appendTo('#cont'); $div.addClass($(this).data('class')); });
.ignore { color: #C00; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="button" class="add" data-class="myElement1">Add clickable</button> <button type="button" class="add" data-class="myElement1 ignore">Add unclickable</button> <div id="cont"></div>
Try to use jQuery('.myElement1').off('click')
or .off()
尝试使用
jQuery('.myElement1').off('click')
或.off()
That should remove the eventHandler.那应该删除 eventHandler。
the answare is :答案是:
jQuery('#cont').off('click', '.myElement1');
but if you have many elements and many events inside #cont (#cont have child and grandchild and soon) you can do this:但是如果你在#cont 中有很多元素和很多事件(#cont 有孩子和孙子,很快)你可以这样做:
jQuery('#cont').off('', '');
That's all就这样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.