[英]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.board
和game.currentPlayer
來訪問當前的tictactoe
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.