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)初始化一個變量,並在點擊時使用簡單的三元語句進行交換來使用。我還為你的重置按鈕添加了功能!