【发布时间】:2016-05-15 21:04:06
【问题描述】:
我正在尝试实现两种方法:启动和停止。问题是,停止似乎不起作用。
const MyObj = function(x) {
this.x = x;
};
MyObj.prototype.start = function(el) {
el.onclick = (function() {
console.log(this.x);
}).bind(this);
};
MyObj.prototype.stop = function(el) {
el.onclick = null;
};
const obj = new MyObj("x");
document.getElementById("checkbox").onchange = function() {
if (this.value) {
obj.start(document.body);
}
else {
obj.stop(document.body);
}
};
我尝试过"" 和function(){} 而不是null,但它们也没有效果。如果我在浏览器控制台中设置onclick 事件,在我调用start 之后,它会起作用。
我该如何解决?
【问题讨论】:
-
请附上minimal reproducible example。您发布的代码无法正确说明您的问题。
-
Your code works。但是这种方法没有意义。
-
是的,我的错,我在使用复选框时不小心将
this.value放入了 if 调用启动/停止而不是this.checked。
标签: javascript event-handling prototype event-listener dom-events