Javascript 如何在类中添加带有html函数回调的事件侦听器?

Javascript 如何在类中添加带有html函数回调的事件侦听器?,javascript,class,addeventlistener,Javascript,Class,Addeventlistener,想象一下,有一个类在页面上生成内容。部分内容应具有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.

想象一下,有一个类在页面上生成内容。部分内容应具有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");
类容器{
构造函数(钩子){
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.querySelector(this.hook).innerHTML=div;
}
fireMe(){
log(“你好!”);
}
init(){
this.addDiv();
}
}
let div=新容器(“应用程序”);
现在得到的错误是fireMe未定义(这是正确的,因为它在全局范围内不可用)


我知道我可以通过先渲染div,然后再添加事件侦听器来添加事件侦听器,但是有没有一种方法可以从
标记中添加事件侦听器,以实际到达
Container.fireMe()
方法?

您必须创建元素->类似的内容

类容器{
构造函数(钩子){
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='解雇我';
div.addEventListener('click',this.fireMe);
document.querySelector(this.hook).innerHTML=div;
}
fireMe(){
console.log('hello!');
}
init(){
this.addDiv();
}
}
const div=新容器(“应用程序”);

永远不要使用内联事件处理程序,因为这样可以避免使用这种20多年的技术

相反,使用现代的、基于标准的代码。如果同时使用创建新的HTML,您将能够更轻松地实现您的目标:

addDiv() {
  const div = document.createElement("div");
  div.textConent = "FIRE ME";
  div.addEventListener("click", this.fireMe);
  document.querySelector(this.hook).innerHTML = div;
}

您应该使用
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");

DOM
中的内联事件查找要在全局范围中声明的函数。改用事件侦听器。另外,我建议将
创建为一个元素,而不是使用HTML字符串和
innerHTML
。谢谢,我想这是最好的选择case@ChrisG哦,我知道。这就是为什么我要使用我的肥皂盒。因为我更灵活,如果我想添加参数,上帝禁止像对待一等公民一样对待函数;)
document.querySelector(this.hook).appendChild(div)
将把节点添加到元素中,OP将用新节点替换当前节点。