首页 > 解决方案 > Javascript - ES6:addEventListener 使用参数调用类方法不起作用

问题描述

这是运行问题的链接:runningExample

我创建一个类:

class button {

    constructor(){       

        var button_id = 99;

        document.getElementById("bu1")
            .addEventListener( "click", this.bu_clicked(button_id) );
    }

    bu_clicked(button_id){
        alert("Hallo: " + button_id);
    }       

}

我在其中添加了一个 addEventListener 以单击按钮:

<button style="width:50px; height:50px;" id="bu1" ></button>

问题是它不能与类调用“this.bu_clicked()”中的参数“button_id”一起正常工作。通过启动脚本,方法“bu_clicked”将立即被调用。

如果我离开这样的参数,“this.bu_clicked”它正在工作,但我需要那个参数!

问候

标签: javascriptclassecmascript-6parametersaddeventlistener

解决方案


作为Gabriel Carneiro的答案的替代方案,您不一定必须将 传递id给点击处理功能。您可以从this对象中获取它,就像this按钮本身一样。

window.onload = function() {  
  obj_button = new button();
};
    
// Option list class
class button {
  constructor(){
    var button_id = 99;
    const button1 = document.getElementById("bu1");
    const button2 = document.getElementById("bu2");
    button1.dataset.buttonId = button_id;
    button2.dataset.buttonId = 100;
    button1.addEventListener( "click", this.bu_clicked );
    button2.addEventListener( "click", this.bu_clicked );
  }

  bu_clicked(e){
    const button = this; // refers to the object that the handler is bound to.
    const button_id = button.dataset.buttonId;
    alert("Hallo: " + button_id);
  }
}
<button style="width:50px; height:50px;" id="bu1">Click me</button>    
<button style="width:50px; height:50px;" id="bu2">Click me as well</button>


推荐阅读