P粉0217082752023-09-04 12:01:27
You have to iterate over each square because querySelectorAll returns multiple nodes and you can't add event listeners directly on it because addEventListener can only work on one node at a time.
I've also added some CSS to the code snippet below so you can see it working when you run it. Ignore this in the final project.
window.onload = () => { const squares = document.querySelectorAll(".square") let currentPlayer = "X"; squares.forEach(square => { square.addEventListener("click", () => { if (square.innerHTML === "") { square.innerHTML = currentPlayer; currentPlayer = currentPlayer === "X" ? "O" : "X"; } }); }); }; document.querySelector('#reset-btn').addEventListener('click', () => { document.querySelectorAll('.square').forEach(square => { square.innerHTML = ""; }); });
#board { margin: 0 auto; width: 50%; } .row { display: grid; grid-template-columns: 1fr 1fr 1fr; } .square { border: 1px solid black; padding: 1rem; cursor: pointer; text-align: center; aspect-ratio: 1/1; display: flex; align-items: center; justify-content: center; } .square:hover { background-color: #CCCCCC; }
<body> <div id="board"> <div class="row"> <div class="square"></div> <div class="square"></div> <div class="square"></div> </div> <div class="row"> <div class="square"></div> <div class="square"></div> <div class="square"></div> </div> <div class="row"> <div class="square"></div> <div class="square"></div> <div class="square"></div> </div> <button id="reset-btn">RESET</button> </div> </body>
Edit: I changed the above code snippet to alternate on click, which can be done by initializing a variable with the current player (X or O) and swapping on click using a simple ternary statement use. I also added functionality to your reset button!