繁体   English   中英

更新for循环内的javascript对象属性?

[英]Update javascript object properties inside of a for loop?

我正在用javascript制作一个井字游戏,我现在正试图让我的x和o出现在我点击空格(div)时。 我有我的系统,以便我的ticTacToe()对象“游戏”可以通过它的对象原型更新。

问题是因为我使用for循环将click事件处理程序附加到具有“space”类的所有div,我无法访问该范围内“游戏”对象的属性。 如果我使用“this”,我指的是div本身。 我已经尝试制作原型函数和构造函数来更新游戏对象的“currentPlayer”,“board”和“turn”属性,但我无法让浏览器识别属性在游戏中宾语。

HTML

<!DOCTYPE html>
<html>
<head>
  <title>Tic-Tac-Toe</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
  <script src="js/script2.js"></script>
</head>
<body>

  <div id="gameBoard">
    <h1 id="msg">Welcome to Tic-Tac-Toe</h1>
    <div id="tl" class="space"></div>
    <div id="tm" class="space"></div>
    <div id="tr" class="space"></div>
    <div id="ml" class="space"></div>
    <div id="mm" class="space"></div>
    <div id="mr" class="space"></div>
    <div id="bl" class="space"></div>
    <div id="bm" class="space"></div>
    <div id="br" class="space"></div>
  </div>
</body>
</html>

JS

function ticTacToe() {
  this.board = [[0,0,0]
               [0,0,0]
               [0,0,0]];
  this.turn = 0;
  this.currentPlayer = 1;
}

ticTacToe.prototype = {
  status: function(){
    console.log("The number of turns played is " + this.turn +
    " and it is player " + this.currentPlayer + "'s turn.");
  },
  attachClicks: function(){
    var spaces = document.getElementsByClassName("space"),
        player = this.currentPlayer;
    for(var i = 0; i<spaces.length; i++){
      spaces[i].addEventListener('click',function(){
        if(player == 1){
          this.style.backgroundImage = "url('x.png')";
          //Update ticTacToe's turn, player, and board
        }
        else {
          this.style.backgroundImage = "url('o.png')";
          //Update ticTacToe's turn, player, and board
        }
      })
    }
  }
}

var game = new ticTacToe();

window.onload = function(){
  game.attachClicks();
}

将另一个变量绑定this

  attachClicks: function(){
    var game = this;
    var spaces = document.getElementsByClassName("space")
    for(var i = 0; i<spaces.length; i++){
      spaces[i].addEventListener('click',function(){
        if(player == 1){
          this.style.backgroundImage = "url('x.png')";
          //Update ticTacToe's turn, player, and board
        }
        else {
          this.style.backgroundImage = "url('o.png')";
          //Update ticTacToe's turn, player, and board
        }
      })
    }

然后你可以在事件监听器函数中引用game.boardgame.currentPlayer来访问当前的tictactoe对象。

暂无
暂无

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

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