我正在试图找出如何最好地使用jQuery删除匿名事件处理程序。
我定义了一个变量来保存我的jQuery对象:
var dom = $('#private-module');
稍后在我的对象中:
run: function () {
var button, that = this;
button = dom.append('<button class="btn">Click Me</button>');
button.on('click', function(event) {
console.log('Clicked!');
that.destroy();
});
},
destroy: function () {
var button;
button = dom.find('.btn');
button.off('click');
}
无论我做什么,我都无法杀死按钮上的点击处理程序。感觉就像我对范围的理解是有缺陷的。在这种情况下删除处理程序的首选方法是什么?我已经尝试了命名空间事件和所有种类,但没有运气,所以我猜它是一些我忽略的简单。也许我甚至不应该为事件处理程序使用匿名函数。
只是为了解决使用.append的理由:
http://jsperf.com/jquery-append-vs-appendto
以下是最终解决方案:
dom.append('<button class="btn">Send Message</button>');
button = dom.find('.btn');
button.on('click', function (event) {
sendTestMessage();
that.destroy();
});
我也同意并理解使用.one方法。谢谢你。
答案 0 :(得分:7)
button = dom.append('<button class="btn">Click Me</button>');
返回dom,而不是按钮,因此您绑定了dom
上的事件处理程序。
更改为:
button = $('<button class="btn">Click Me</button>').appendTo(dom);
这是working demo。
答案 1 :(得分:1)
问题是button
是dom
而不是.btn
:
button = dom.append('<button class="btn">Click Me</button>');
//a console.log(button) here reveals that button is "dom"
//and thus you are adding a handler to "dom
button.on('click', function(event) {
console.log('Clicked!');
that.destroy();
});
执行此操作的一种方法是感谢.on()
的委托权限是将要绑定处理程序的元素的子选择器添加为第二个参数。
button.on('click', '.btn' function(event) {
//the value of "this" in here is the ".btn"
console.log('Clicked!');
that.destroy();
});
在销毁中,我们使用.off()
以及与.btn
相关的第二个参数:
button.off('click', '.btn');