18910140161

JavaScript-为什么当页面加载时,我的console.log语句运行了9次,每次都为0?-堆栈溢出

顺晟科技

2022-10-19 12:50:56

38

我正在进行井字游戏,当玩家一在棋盘上有5个x导致平局时,我试图发送警报。

基本上,玩家一总是先走,从X开始,如果玩家一的计数器命中5,我想发送警报。但是每当我控制。log p1Counter时,在开始播放之前,页面加载时,我会得到0 9次。

<!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='styles.css'>
    <title>Tic Tac Toe</title>
  </head>
  <body>
    <h1 id='heading'>Tic-Tac-Toe World Championship 2021</h1>
    <div id='game-board'>
      <table>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
      </table>
    </div>
    <div id=button-box>
      <button type='button'>Reset!</button>
    </div>
    <script src='app.js'></script>
  </body>
</html>

以下是javascript代码:

<!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='styles.css'>
    <title>Tic Tac Toe</title>
  </head>
  <body>
    <h1 id='heading'>Tic-Tac-Toe World Championship 2021</h1>
    <div id='game-board'>
      <table>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
      </table>
    </div>
    <div id=button-box>
      <button type='button'>Reset!</button>
    </div>
    <script src='app.js'></script>
  </body>
</html>


顺晟科技:

当页面加载时,循环只运行1次,那么再次运行的代码只有和更新的部分。

并且由于循环得到9个元素,所以要运行9次。

因为在赋值之后,它返回到new循环,永远不会增加变量。

<!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='styles.css'>
    <title>Tic Tac Toe</title>
  </head>
  <body>
    <h1 id='heading'>Tic-Tac-Toe World Championship 2021</h1>
    <div id='game-board'>
      <table>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
      </table>
    </div>
    <div id=button-box>
      <button type='button'>Reset!</button>
    </div>
    <script src='app.js'></script>
  </body>
</html>

唯一的增加当您单击td标记时,我添加了一些样式来显示该框,以便于查看。

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航