javascript - 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”它正在工作,但我需要那个参数!
问候
解决方案
作为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>
推荐阅读
- python - 我想使用 python 将 .wav 文件从我当前的系统复制到 linux 服务器
- android - 三星 Galaxy S8 android 版本 8.0.0 中未生成 FCM 实例 ID
- python - 更改缓冲区大小以提高 python 中的复制速度
- css - 选择器之间的空格是什么意思?
- php - Laravel Excel 正在将日期从标题转换为一些数字
- .htaccess - 带有 GET 参数的 .htaccess mod_rewrite 不会重定向
- android - 为什么 URL 响应为 Null?
- arrays - CString到字节和字节到CByteArray转换-MFC
- multithreading - 使用 redis 多线程,使用 jedis 连接池
- c++ - 如何使 id3lib 在 C++ Builder 10.2 中工作?