gpt4 book ai didi

javascript - onClick 函数在更改时运行?

转载 作者:行者123 更新时间:2023-11-28 16:57:02 25 4
gpt4 key购买 nike

我正在处理一个 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时,你需要传入函数而不执行它们。要解决此问题,请更改设置按钮的方式 -

this.setButton1(genericFunction(), "Button 1");

this.setButton1(genericFunction, "Button 1");

关于javascript - onClick 函数在更改时运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58863948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com