简体   繁体   English

(JavaScript)如何防止用户单击已被单击的井字游戏方块?

[英](JavaScript) How do I prevent a user from clicking in a tic tac toe square that has already been clicked on?

I'm making a 2 player tic tac toe game and I can not find out how to prevent a player from clicking on a square that has already been clicked on. 我正在制作2人tic TAC Toe游戏,我无法找出如何防止玩家点击已经被点击的方格。

I have tried adding if (squareId.innerText = "" ) but this doesn't seem to work. 我尝试添加if (squareId.innerText = "" )但这似乎不起作用。 Any suggestions, please? 有什么建议吗?

var player = [];
var players = ['X', 'O'];
player[0] = "Player 1";
player[1] = "Player 2";
var turn = 0;
var cells = document.querySelectorAll(".cell");



const winCombos = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 4, 8],
  [6, 4, 2],
  [2, 5, 8],
  [1, 4, 7],
  [0, 3, 6],
]


startGame();


function startGame() {
  document.querySelector('.endgame').style.display = "none";
  for (var i = 0; i < cells.length; i++) {
    cells[i].innerText = '';
    cells[i].style.removeProperty('background-color');
    cells[i].addEventListener('click', changeTurn)
  }
}


function changeTurn(square) {
  console.log("square# " + square.target.id);
  console.log("Player " + players[turn]);

  let squareId = square.target.id;


  if (squareId.innerText = "" ) {
  document.getElementById(squareId).innerText = players[turn] ;
  if (turn == 0) {turn = 1;
} else { turn = 0; }

  }

}

try add this css property when a cell is clicked: 尝试在单击单元格时添加以下css属性:

pointer-events: none; 指针事件:无;

this will make the cell not clickable... 这将使该单元格不可点击...

You could remove even listener after clicking so element will not listen anymore: 您可以在单击后甚至删除侦听器,以使元素不再侦听:

function changeTurn(square) {
    square.target.removeEventListener('click', changeTurn);
    // the rest
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM