想象一下,有一个类可以在页面上生成内容。内容的一部分应具有以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()
方法? / p>
答案 0 :(得分:3)
您必须创建元素->类似这样的
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');
答案 1 :(得分:2)
请不要使用内联事件处理程序,因为有many reasons会避免使用这种已有20多年历史的技术,但这种技术不会消失。
相反,请在.addEventListener()
上使用基于标准的现代代码。如果您这样做并使用DOM API制作新的HTML,则可以更轻松地实现目标:
addDiv() {
const div = document.createElement("div");
div.textConent = "FIRE ME";
div.addEventListener("click", this.fireMe);
document.querySelector(this.hook).innerHTML = div;
}
答案 2 :(得分:0)
您应该使用document.createElement()
而不是字符串来创建元素
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.innerHTML = "Fire Me";
div.addEventListener("click",this.fireMe);
document.querySelector(this.hook).appendChild(div);
}
fireMe() {
console.log("hello!");
}
init() {
this.addDiv();
}
}
let div = new Container("app");