是否可以创建涉及按钮的 if 语句

Is it possible to create an if statement involving buttons?

本文关键字:按钮 if 语句 创建 是否      更新时间:2023-09-26

在我的程序中有多个按钮,我想发生的是有一个函数只有在按下所有按钮时才运行。我正在考虑有一个 if 语句,该语句需要单击所有三个按钮,然后函数将运行。这可能吗?

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

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

希望对:)有所帮助

将来,当你问这样的问题时,你应该有一些工作要分享。但是,这里有一种实现它的方法。我已经对它进行了大量评论,以便您可以看到我所做的工作,因为我猜您至少是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();" />