【问题标题】:Is it possible to create an if statement involving buttons?是否可以创建一个涉及按钮的 if 语句?
【发布时间】:2015-01-15 03:35:56
【问题描述】:

在我的程序中有多个按钮,我希望有一个功能只有在所有按钮都被按下时才会运行。我正在考虑有一个 if 语句,它需要单击所有三个按钮,然后该函数将运行。这可能吗?

【问题讨论】:

  • 存储 3 个单独的变量。每次按下其中一个按钮时,将该按钮变量的值设置为true,然后检查所有三个变量是否都是true,如果是,则运行您的自定义函数。这也可以通过一个包含三个值而不是三个变量的数组来完成。
  • 是的。如果我需要更多帮助,您应该向我们展示一些代码。
  • 谢谢。我可以看到一些可以代表它的代码吗?
  • 没有。该站点可以很好地帮助您调试、修复和理解代码,但该站点并不是为了让其他人为您编写代码。尝试自己在JSFiddle 中编写它,看看你能走多远。如果您遇到困难,那么回到这里,向我们展示您目前的成果,我们或许可以为您提供帮助。
  • 如果您需要帮助,请告诉我们您能走多远。

标签: javascript button if-statement


【解决方案1】:

我不确定我是否完全理解这一点,但是如果您想检查是否按下了所有按钮。首先,您必须创建一个函数来知道按钮是否被按下,然后您将创建 if 语句,如下例所示:

if(button1.isPressed() && button2.isPressed() && button3.isPressed && button4.isPressed){
    // Do whathever you want
};

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    以后,当你提出这样的问题时,你应该有一些工作可以分享。但是,这是一种实现方式。我已经对它进行了大量评论,以便您可以看到我所做的事情,因为我猜您至少是 javascript 新手。

    //array to hold whether each button has been clicked
    var buttonsClicked = [false, false, false]; 
    
    //function to check if any button has not been clicked
    function allButtonsClicked() {
      //loop through 0 to the highest index in the array (at the moment, this will be 2)
      for (i = 0; i < buttonsClicked.length; i++) {
        if (!buttonsClicked[i])
          return false; //return false if the value is false, no need to keep looping
      }
      return true; //return true if the loop completes without returning false
    }
    
    //function to handle button clicks. Takes an argument which will be hardcoded into the input tag
    function buttonClicked(button) {
      //set the specified button to true
      buttonsClicked[button] = true;
      if (allButtonsClicked()) //call the function to check if all buttons are clicked
        alert('All buttons have been clicked'); //if true, do the alert
    }
    
    function resetButtons() { //function to set all the "click states" in the array back to false
      for (i = 0; i < buttonsClicked.length; i++) { //again, loop from 0 to the highest index in the array
        buttonsClicked[i] = false; //set each button to false
      }
    }
    <input type="button" value="Zero" onclick="buttonClicked(0);" />
    <input type="button" value="One" onclick="buttonClicked(1);" />
    <input type="button" value="Two" onclick="buttonClicked(2);" />
    <br />
    <input type="button" value="Reset" onclick="resetButtons();" />

    【讨论】:

      猜你喜欢
      • 2015-01-07
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      相关资源
      最近更新 更多