我试图通过一个类方法将事件监听器添加到一个元素中,你能告诉我我缺少了什么,它没有工作吗?
class PumpBasic
{
constructor(_name)
{
this.name = _name;
}
Foo()
{
this.element = document.getElementById(this.name + "AutoManualSwitch");
this.element.addEventListener('click', myFunction, false);
}
myFunction()
{
console.log("clicked");
}
}
pump1 =new PumpBasic("pump1");
<input id="pump1AutoManualSwitch" data-on="Manual" data-off="Auto" data-onstyle="primary" type="checkbox" data-toggle="toggle" data-width="75" data-height="30">
如果你要通过 myFunction
方法来添加EventListener作为一个回调函数,你需要使用这个方法来引用它。
你还需要绑定它以使它正常工作。 如果你不绑定它,全局事件对象会在调用时重新定义它。
这应该可以工作。
class PumpBasic
{
constructor(_name)
{
this.name = _name;
this.myFunction = this.myFunction.bind(this)
}
Foo()
{
this.element = document.getElementById(this.name + "AutoManualSwitch");
this.element.addEventListener('click', this.myFunction, false);
}
myFunction()
{
console.log("clicked");
}
}
const pump1 = new PumpBasic("pump1");
pump1.Foo()