I use the following to bind click
event on certain elements that are inserted into DOM on the fly.
jQuery('#cont').on('click', '.myElement1', ....);
In this case, how would I unbind
them?
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.
You cannot unbind the event handler on .myElement1
as it was bound to #cont
. There's no way to remove the event from that single .myElement1
instance without affecting all the other ones.
What you could do as a workaround is to add another class to the .myElement
and then exclude that class from the dynamic selector:
$('#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()
That should remove the 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:
jQuery('#cont').off('', '');
That's all
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.