我目前有四个按钮当按下所有按钮时我会收到警报但我想要的是当我们按下按钮1和按钮3或按钮1和按钮2或按钮3和按钮4的按钮组合时,应显示不是点击所有按钮时
<html>
<head>
<title>Display</title>
</head>
<body>
<center>
</br></br></br></br></br></br>
<button id="button1" class="tictac" type="button" onclick="button1check()">button1</button>
<button id="button2" type="button" onclick="button2check()">button2</button></br></br>
<button id="button3" type="button" onclick="button3check()">button3</button>
<button id="button4" class="tictac" type="button" onclick="button4check()">button4</button>
</center>
<script type="text/javascript">
button1clicked = 0;
button2clicked = 0;
button3clicked = 0;
button4clicked = 0;
function button1check() {
button1clicked = 1;
if (button1clicked == 1 && button2clicked == 1 && button3clicked == 1 && button4clicked == 1 ) {
alert('you win!');
button1clicked = 0;
button2clicked = 0;
button3clicked = 0;
button4clicked = 0;
}
}
function button2check() {
button2clicked = 1;
if (button1clicked == 1 && button2clicked == 1 && button3clicked == 1 && button4clicked == 1) {
alert('you win!');
button1clicked = 0;
button2clicked = 0;
button3clicked = 0;
button4clicked = 0;
}
}
function button3check() {
button3clicked = 1;
if (button1clicked == 1 && button2clicked == 1 && button3clicked == 1 && button4clicked == 1) {
alert('you win!');
button1clicked = 0;
button2clicked = 0;
button3clicked = 0;
button4clicked = 0;
}
}
function button4check() {
button4clicked = 1;
if (button1clicked == 1 && button2clicked == 1 && button3clicked == 1 && button4clicked == 1 ) {
alert('you win!');
button1clicked = 0;
button2clicked = 0;
button3clicked = 0;
button4clicked = 0;
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
我会提出一个不同的方法。使用以下代码,您可以在winner
数组中设置获胜组合。如果clickcount等于按钮计数并且未点击获胜组合,则重置游戏。
let winner = [[1, 3], [2,4]];
let clicked = [];
let btns = Array.from(document.getElementsByTagName("button"));
btns.forEach(b => {
b.addEventListener('click', function(el) {
let number = el.target.id.replace(/[^0-9]/g, "");
clicked.push(number);
if (winner.some(w => w.sort().join("") === clicked.sort().join(''))) {
alert("You're a winner");
clicked = [];
} else if (clicked.length === btns.length) {
clicked = [];
alert("Nah!");
}
})
})
<button id="button1" class="tictac" type="button">button1</button>
<button id="button2" type="button">button2</button>
<button id="button3" type="button">button3</button>
<button id="button4" class="tictac" type="button">button4</button>
答案 1 :(得分:0)
以下是您的示例,但您的代码也正常运行。
var btns = [0,0,0,0];
function checkButtons() {
if (btns[0] == 1 && btns[1] == 1 && btns[2] == 1 && btns[3] == 1) {
alert('You win!');
for (var i = 0; i < btns.length; i++) {
btns[i] = 0;
}
}
}
function btnClick(n) {
btns[n - 1] = 1;
checkButtons();
}
<center>
</br>
</br>
</br>
</br>
</br>
</br>
<button onclick="btnClick(1)">button1</button>
<button onclick="btnClick(2)">button2</button>
</br>
</br>
<button onclick="btnClick(3)">button3</button>
<button onclick="btnClick(4)">button4</button>
</center>