TicTacToe - 麻烦交替球员

时间:2018-04-18 22:43:02

标签: javascript tic-tac-toe

首先点击鼠标即可获得预期的' x'标记,但下一次鼠标单击导致警报("播放器o:平铺已被选中),即使网格项为空。我做错了什么?

在HTML正文中,我创建了一个3x3网格,共9个gridItems。

$(document).ready(function(){

        let grid = $("#grid-container") 
        let gridItem = $(".grid-item")

        function select(){ 
            for (i = 0; i < gridItem.length; i++){
                gridItem[i].addEventListener("click", function(){ 
                    if ($(this).html() == ""){
                        $(this).html("x");
                        nextSelect(); 
                    } else {alert ("Player X: tile has already been selected"); select()}
                })
            }
        }

        function nextSelect(){
            for (i = 0; i < gridItem.length; i++){
                gridItem[i].addEventListener("click", function(){  
                    if ($(this).html() == ""){
                        $(this).html("o");
                        select();
                    } else {alert ("Player o: tile has already been selected"); nextSelect()}   
                })
            }   
        }

        select()

    });   

1 个答案:

答案 0 :(得分:1)

addEventListener只能执行一次。您的问题是您要添加多个事件处理程序。下面的代码段中可能的版本。

这个想法是你只需要一个函数并将它附加到每个单元格只有一次click事件,这是通过jQuery .click(callback)完成的。要管理转弯,您可以使用布尔变量(isTurnOfPlayerOne)。

$(document).ready(function() {
  let isTurnOfPlayerOne = true;
  $(".grid-item").click(handleClick);

  function handleClick() {
    if ($(this).html() == "&nbsp;") {
      let symbol = (isTurnOfPlayerOne ? "x" : "o");
      $(this).html(symbol);
    } else {
      alert("Tile has already been selected");
    }

    isTurnOfPlayerOne = !isTurnOfPlayerOne;
  }

});
.grid-item {
  width: 40px;
  height: 40px;
  display: inline-block;
  border: solid 1px #000;
  text-align: center;
  margin-bottom: 3px;
  line-height: 30px;
  font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="grid-container">
  <div class="grid-item">&nbsp;</div>
  <div class="grid-item">&nbsp;</div>
  <div class="grid-item">&nbsp;</div>
  <br/>
  <div class="grid-item">&nbsp;</div>
  <div class="grid-item">&nbsp;</div>
  <div class="grid-item">&nbsp;</div>
  <br/>
  <div class="grid-item">&nbsp;</div>
  <div class="grid-item">&nbsp;</div>
  <div class="grid-item">&nbsp;</div>
</div>