想象一下,有一个在页面上生成内容的类.部分内容应该在html中附加事件监听器,例如onclick = function().
如何确保从构造html的类中调用该函数?
class Container {
constructor(hook) {
this.hook = "#" + hook;
this.addDiv = this.addDiv.bind(this);
this.fireMe = this.fireMe.bind(this);
this.init = this.init.bind(this);
this.init();
}
addDiv() {
const div = `<div onclick="fireMe()">FIRE ME</div>`;
document.querySelector(this.hook).innerHTML = div;
}
fireMe() {
console.log("hello!");
}
init() {
this.addDiv();
}
}
let div = new Container("app");
现在得到fireMe未定义的错误(这是正确的,因为它在全局范围内不可用).
我知道我可以通过首先渲染div而不是添加事件监听器来添加事件监听器,但是有没有办法从< div>中添加事件监听器.标签实际到达Container.fireMe()方法?
解决方法:
你必须创建元素 – >这样的事情
class Container {
constructor (hook) {
this.hook = '#' + hook;
this.addDiv = this.addDiv.bind(this);
this.fireMe = this.fireMe.bind(this);
this.init = this.init.bind(this);
this.init();
}
addDiv () {
const div = document.createElement('div');
div.textContent = 'FIRE ME';
div.addEventListener('click', this.fireMe );
document.querySelector(this.hook).innerHTML = div;
}
fireMe () {
console.log('hello!');
}
init () {
this.addDiv();
}
}
const div = new Container('app');