首页 > 解决方案 > 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。

标签: javascriptonclick

解决方案


调用setButtonN时,需要传入函数而不执行它们。要修复它,请更改您设置按钮的方式 -</p>

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

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


推荐阅读