P粉0217082752023-09-04 12:01:27
你必须对每个方块进行迭代,因为querySelectorAll返回多个节点,你不能直接在上面添加事件监听器,因为addEventListener一次只能对一个节点起作用。
我还在下面的代码片段中添加了一些CSS,这样当你运行它时,你可以看到它的工作情况。在最终项目中忽略这个。
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>
编辑:我将上面的代码片段更改为点击时交替,可以通过用当前玩家(X或O)初始化一个变量,并在点击时使用简单的三元语句进行交换来使用。我还为你的重置按钮添加了功能!