这里是我的井字棋游戏的HTML:井字JavaScript的帮助(我没有得到我想要的警报)
<html>
<head>
<title>Tic Tac Toe</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>Tic-Tac-Toe</h1>
<div id="message"></div>
<table border="3">
<tr>
<td class="Square" id="s1" onclick="nextMove(this);"></td>
<td class="Square" id="s2" onclick="nextMove(this);"></td>
<td class="Square" id="s3" onclick="nextMove(this);"></td>
</tr>
<tr>
<td class="Square" id="s4" onclick="nextMove(this);"></td>
<td class="Square" id="s5" onclick="nextMove(this);"></td>
<td class="Square" id="s6" onclick="nextMove(this);"></td>
</tr>
<tr>
<td class="Square" id="s7" onclick="nextMove(this);"></td>
<td class="Square" id="s8" onclick="nextMove(this);"></td>
<td class="Square" id="s9" onclick="nextMove(this);"></td>
</tr>
</table>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
我的JavaScript代码如下。
var turn = "X";
function setMessage(msg) {
document.getElementById("message").innerText = msg;
}
function nextMove(square) {
if (square.innerHTML == "X" || square.innerHTML == "O") {
alert('It has already been selected');
} else {
square.innerText = turn;
switchTurn();
}
};
function switchTurn() {
if (checkforWinner(turn)) {
alert("Congratulations, " + turn + "! You win");
} else if (turn == "X") {
turn = "O";
setMessage("It's " + turn + "'s turn!");
} else {
turn = "X";
setMessage("It's " + turn + "'s turn!");
}
}
function checkforWinner(move) {
var result = false;
if (checkRow(1,2,3, move) ||
checkRow(4,5,6, move) ||
checkRow(7,8,9, move) ||
checkRow(1,4,7, move) ||
checkRow(2,5,8, move) ||
checkRow(3,6,9, move) ||
checkRow(1,5,9, move) ||
checkRow(3,5,7, move)) {
result = true;
}
return result;
}
function checkRow(a,b,c, move) {
var result = false;
if (getBox(a) === move && getBox(b) === move && getBox(c) === move) {
result = true;
}
return result;
}
function getBox(number) {
document.getElementById("s" + number).innerText
}
用户从获得三连胜O公司或X在所有可能的方式获胜后,我要警告说:“恭喜,X/Y!你赢了”
我做了if(checkforWinner(turn)) {
和在switchTurn
函数中,alert("Congratulations, " + turn + "! You win");
之后立即显示警告。但是,当我测试我的代码时,在用户获得三个O或X的直线后,警报不会弹出。
实际上是否存在代码问题,或者是否将代码放在了我不应该存在的地方?我完全不知道。
此外,根据http://stackoverflow.com/questions/1359469/innertext-works-in-ie-but-not-in-firefox,并非每个浏览器都支持.innerText。考虑使用.innerHTML。 – Tirzono
@Tirzono'innerText'是IE的老办法,从引入'innerHTML'的时候开始。 'innerHTML'起飞,'innerText'不起作用,而我们有'textContent'。耶为标准化! –