我有一个 jQuery 插件,它在某些元素上附加事件处理程序。
在插件的 destroy 方法中,我希望删除这些事件处理程序,但仅删除该插件实例添加的事件处理程序。
如果我这样做 .off('.myPlugin');
它可能会删除其他插件实例添加的事件处理程序,但我不希望这样。
我想问的可以吗?
最佳答案
jQuery 有事件命名空间,正好可以用于此目的。
您可以为添加的事件命名,这样就可以在不删除其他事件处理程序的情况下删除它们,因此在插件中您将添加像这样的所有事件处理程序
$( "p" ).on( 'click.pluginName', function(event) {
// do stuff on click
});
当您想要删除该点击处理程序,并且仅删除该点击处理程序,而不是其他点击处理程序时,您可以这样做
$( "p" ).off( 'click.pluginName');
这就是插件中通常的做法。
<小时/>如果您需要识别插件的每个实例,您可以使用标志、计数器或其他任何东西。
像这样的东西会起作用
$.fn.plugin = function() {
var self = this,
count = $.fn.plugin.counter++;
$(this).on('click.pluginName' + count, function() {
// do stuff on click
});
this.destroy = function() {
self.off('click.pluginName' + count)
}
}
$.fn.plugin.counter = 0;
<小时/>
或其他变体
$.fn.plugin = function(arg) {
if (arg == 'destroy') {
var count = $(this).data('count');
$(this).off('click.pluginName' + count);
}else{
var count = $.fn.plugin.counter++;
$(this).data('count', count).on('click.pluginName' + count, function() {
alert('clicked')
});
}
return this;
}
$.fn.plugin.counter = 0;
关于javascript - 如何仅删除实例中添加的事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25020672/