在单击事件处理程序中,我有 3 个函数。为什么第三个功能在前两个功能完成之前执行?

Inside a click event handler I have 3 functions. Why is the 3rd function executing before the first two are finished?

我正在 javascript 中编写一个井字游戏。单击板上的方块时,将按以下顺序调用三个函数。

  1. move() - 此函数在点击的方块中显示玩家角色(X 或 O)。
  2. computer() - 此函数确定 select 的最佳方格,然后在所选方格中显示计算机字符(X 或 O)。
  3. gameOver() - 此函数检查玩家 1 或玩家 2 是否赢得了比赛。如果游戏获胜,则会收到一条消息,宣布获胜者并清除棋盘。

    $(".num").on("click", function(){
      var square = $(this).attr("id");
    
      //Display users' moves, push moves into the correct user's moves 
      //array, remove the chosen square from the open array, and increment 
      //the count.
      move(square);
    
      //If the user has chosen to play the computer and the board is not 
      //full, execute the computer's move.
      if(twoPlayers===false && count<9){
        computer();
      }
    
      //Check for a win or draw.
      gameOver();
    })
    

    为什么一局赢了,棋盘还没显示就被清空了??

这是link到codepen

在显示获胜着法之前没有被清除。它发生得太快了,你看不到最后一步。将你的 gameOver() 调用包裹在 setTimeout 中,让它有足够的时间看到移动显示,如下所示:

$(".num").on("click", function(){
    var square = $(this).attr("id");

    //Display users' moves, push the user's moves into the correct moves array, remove the chosen square from the open array, and increment the count.
    move(square);

    //If the user has chosen to play the computer and the board is not full, execute the computer's move.
    if(twoPlayers===false && count<9){
        computer();
    }

    //Check for a win or draw.
    setTimeout(gameOver, 3000);
})

这是更新后的点赞codepen

我还没有仔细阅读您的源代码以查看您更新显示的位置。但是,我在每个函数的末尾创建了一个带有 alert 的新 codepen。即使在最后一步,您也可以清楚地看到每个功能都按顺序执行。游戏结束功能清除棋盘,您会看到最后一步没有显示。