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

时间:2015-01-15 03:35:57

标签: javascript button if-statement

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

2 个答案:

答案 0 :(得分:0)

我不确定我是否完全明白,但是如果你想检查是否所有的按钮都被按下了。首先,你必须创建一个函数来知道按钮是否被按下然后你做了if和if语句,如下一个例子:

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

希望它有所帮助:)

答案 1 :(得分:0)

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