我正在制作一个井字棋游戏。我已经将表格单元格设置为可点击,一旦点击它们,它们就会运行一个名为 playPVPGame 的函数。首先,随机选择 O 和 X 作为先行者。我在页面的一 Angular 有文字来指示轮到谁了。最初,文本将是“O 首先”或“X 首先”。之后,根据回合,它将更改为“X 是下一个”或“O 是下一个”。问题是在初始文本之后,转弯并没有像我想要的那样来回。
var $ = function(id) {
return document.getElementById(id);
};
var newGameAction = function()
{
//clear table
$("c1").innerHTML = "";
$("c2").innerHTML = "";
$("c3").innerHTML = "";
$("c4").innerHTML = "";
$("c5").innerHTML = "";
$("c6").innerHTML = "";
$("c7").innerHTML = "";
$("c8").innerHTML = "";
$("c9").innerHTML = "";
};
var pVpAction = function(elem)
{
var outputTect;
var turnCounter = 0;
var first_Turn = Math.floor(Math.random() * 2);
$("firstTurn").innerHTML = first_Turn;
first_turn = $("firstTurn").innerHTML;
if(first_turn == 0)
{
message = "O goes first";
}
if(first_turn == 1)
{
message = "X goes first";
}
$("goNext").innerHTML = message;
};
var playPVPGame = function(elem)
{
var turn = $("goNext").innerHTML;
var message;
if(turn == "O goes first")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
turn = "X is next";
$("goNext").innerHTML = turn;
}
if(turn == "X goes first")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
turn = "O is next";
$("goNext").innerHTML = turn;
}
//does not work
/*if($("goNext").innerHTML = "X is next")
{
$("newGame").disabled = true;
}*/
message = $("goNext").innerHTML;
if(message == "X is next")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
message = "O is next";
$("goNext").innerHTML = message;
}
if(message == "O is next")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
message = "X is next";
$("goNext").innerHTML = message;
}
};
window.onload = function() {
$("newGame").onclick = newGameAction;
$("playerVplayer").onclick = pVpAction;
};
table {width:100%}
table tr td{border:1px solid #000;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="firstTurn"> </span>
<span id= "goNext"> </span>
<table class = "board">
<tr>
<td id = "c1" onclick="playPVPGame(this)" > . </td>
<td id = "c2" onclick="playPVPGame(this)"> . </td>
<td id = "c3" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c4" onclick="playPVPGame(this)"> . </td>
<td id = "c5" onclick="playPVPGame(this)"> . </td>
<td id = "c6" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c7" onclick="playPVPGame(this)"> . </td>
<td id = "c8" onclick="playPVPGame(this)">. </td>
<td id = "c9" onclick="playPVPGame(this)"> .</td>
</tr>
</table>
<input type="button"
id= "newGame"
value="New Game"/>
<input type="radio"
id= "playerVplayer"
value="Player vs Player"/>
<input type="radio"
id= "playerVcpu"
value="Player vs CPU"/>
最佳答案
将当前玩家(“X”或“O”)存储在变量中,而不是从 GUI 中读取。
从 GUI 中读取内容是不好的做法,您必须问这个问题才能说明为什么会出现这种情况。
关于javascript - 可点击的 html 表格单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248815/