javascript - onClick 函数在更改时运行?
问题描述
我正在处理一个 HTML 文件,其中包含一些带有 onClick 属性的按钮。我找到了更改运行函数的方法,但是当我更改它时,新函数运行。我看过其他类似的问题,但我找不到答案。
class buttonController {
constructor(){
this.button1 = document.getElementById("button1");
this.button2 = document.getElementById("button2");
this.button3 = document.getElementById("button3");
}
setButton1(p_func, text){
this.button1.textContent = text;
document.getElementById("button1").onclick = p_func; //I've tried using .setAttribute too
}
setButton2(p_func, text){
this.button2.textContent = text;
document.getElementById("button2").onclick = p_func;
}
setButton3(p_func, text){
this.button3.textContent = text;
document.getElementById("button3").onclick = p_func;
}
detectState(){ //the issue is here. if you set the function to a new function, it will run.
if (g_state == "COMBAT"){
this.setButton1(genericFunction(), "Button 1");
this.setButton2(anotherFunction(), "Button 2");
this.setButton3(oneMoreFunction(), "Button 3");
}
if (g_state == "IDLE"){
this.setButton1(function(){consoleController.log("button1 pressed");}, "button 1");
this.setButton2(function(){consoleController.log("button2 pressed");}, "button 2");
this.setButton3(function(){consoleController.log("button3 pressed");}, "button 3");
}
}
}
如果可能,我想避免使用 jQuery。
解决方案
调用setButtonN
时,需要传入函数而不执行它们。要修复它,请更改您设置按钮的方式 -</p>
this.setButton1(genericFunction(), "Button 1");
至
this.setButton1(genericFunction, "Button 1");
推荐阅读
- python - 如何枚举列表但从 1 开始索引?
- reactjs - 如何使 tsconfig 与 webpack 提供插件一起使用?
- r - 如果计算相对拒绝频率,如何衡量与显着性水平是否显着不同?(R中的正态性测试)
- android-studio - 无法在离线模式下运行或构建我的简单应用程序
- utf-8 - MTProto 字符串类型:长度是以字节还是 UTF-8 字符串长度来衡量的?
- c++ - 标识符未定义 C++
- azure - 删除 Azure Active Directory (ADD) 和关联门户
- flutter - 从飞镖列表中删除重复项
- javascript - 如何在本机反应中切换布尔值?
- algorithm - 如何处理整数平方根方法中的大输入?