这是运行问题的链接: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”就可以了,但是我需要该参数!
问候
答案 0 :(得分:1)
尝试一下:
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
需要一个字符串和一个函数,您正在传递this.bu_clicked
返回的undefined
。如果按照我的方式写,那么您正在传递一个闭包,该闭包调用this.bu_clicked
并传递button_id
。 (PS:大括号是可选的,我只是为了便于理解而放置)
答案 1 :(得分:1)
作为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>
答案 2 :(得分:-1)
您应该bind
处理程序到元素:
document.getElementById("bu1")
.addEventListener("click", this.bu_clicked.bind(button_id));