我正在使用 HTML、CSS 和 JavaScript 制作井字游戏。我尝试添加一个事件侦听器,以便在单击按钮时进行检查,并添加一个条件来检查轮到谁了。单击时应显示按钮已单击,并在单击按钮时根据条件打印文本。
let boxes = document.querySelectorAll(".box");
let turnO = true;
const winningPatterns = [
[0, 1, 2],
[0, 3, 6],
[0, 4, 8],
[1, 4, 7],
[2, 5, 8],
[2, 4, 6],
[3, 4, 5],
[6, 7, 8],
];
boxes.forEach((box) => {
box.addEventListener("onclick", () => {
console.log("box was clicked");
if (turnO) { //checking whether it is the turn O's turn
box.innerText = "O";
turnO = false;
} else {
box.innerText = "X"; //checking whether it is the turn of X's
turnO = true;
}
});
});
/* CSS added by Editor for demo purpose */
.game {
display: grid;
grid-template-columns: repeat(3, max-content);
grid-gap: 0.5em;
.box {
aspect-ratio: 1;
width: 2em;
}
}
<main>
<h1>Tic Tac Toe</h1>
<div class="container">
<div class="game">
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
</div>
</div>
<button id="reset-btn">Reset Game</button>
</main>
我希望它显示按钮是否被单击以及轮到谁但按钮不起作用。 我已将脚本文件与 html 直接连接。我想知道我哪里出错了。
即使发生了
onclick
事件,您也弄错了 click
。如果您使用 onclick
,则必须使用 element.onclick = function() { ... }
,它将事件附加到元素并覆盖所有先前的事件。addEventListener
附加事件,则必须侦听 click
事件,例如 element.addEventListener('click', function() { ... })
。
但是,更明智的做法是在容器上使用事件委托,并检查单击的元素是否是按钮以及按钮是否为空:
const PLAYERS = ['X', 'O'];
let turn = 0;
const winningPatterns = [
[0, 1, 2],
[0, 3, 6],
[0, 4, 8],
[1, 4, 7],
[2, 5, 8],
[2, 4, 6],
[3, 4, 5],
[6, 7, 8],
];
document.querySelector('.container').addEventListener('click', function(e) {
if (e.target.tagName === 'BUTTON' && e.target.textContent === '') {
e.target.textContent = PLAYERS[turn];
turn = (turn + 1) % PLAYERS.length;
}
})
/* CSS added by Editor for demo purpose */
.game {
display: grid;
grid-template-columns: repeat(3, max-content);
grid-gap: 0.5em;
.box {
aspect-ratio: 1;
width: 2em;
}
}
<main>
<h1>Tic Tac Toe</h1>
<div class="container">
<div class="game">
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
<button class="box"></button>
</div>
</div>
<button id="reset-btn">Reset Game</button>
</main>