我一直试图解决这个问题几个小时,但我最后感觉自己像个白痴。这是编程类,代码应该做的是显示" x"在一个盒子里,当它被点击甚至转弯和一个" o"奇怪的。现在,单击框时只显示" x" s。我想我搞砸了涉及全局变量的地方。有人可以帮我弄清楚我做错了什么吗?
以下是HTML和Javascript代码:
var markCount
window.onload = function() {
var i;
var prefix;
i = 0; //initializing i
prefix = "square"; //defining prefix
markCount = getMarkCount();
while (i !== null) //will keep repeating until i is null
{
document.getElementById(prefix + i).onclick = markTheSquare; //finds element Id by prefix and i number and references clicked function
i = i + 1; //increments i
} //while
};
function markTheSquare() {
this.onclick = null;
this.innerHTML = getXorO; //causes x or o to be displayed in current element
markCount = markCount + 1;
}
function getMarkCount() {
return setMarkCount(markCount);
}
function setMarkCount(markCount) {
markCount = 0;
}
function getXorO() {
var string;
var p;
string = "xo"
p = getMarkCount % 2;
return string.charAt(p);
}

<!DOCTYPE html>
<html lang="en">
<head>
<title> Tic-Tac-Toe Part 2 </title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<script src="ticTacToePart1.js" type="text/javascript"></script>
<style type="text/css">
body
{
font-size:12pt;
margin-left:auto;
margin-right:auto;
padding-top:5em;
width:33em;
}
.square
{
float:left;
font-size:8em;
height:1.25em;
text-align:center;
width:1.25em;
}
.border1
{
border-left:solid;
border-right:solid;
}
.border2
{
border-bottom:solid;
border-top:solid;
}
</style>
</head>
<body>
<div id=page>
<div class="square" id=square0></div>
<div class="square border1" id=square1></div>
<div class="square" id=square2></div>
<div class="square border2" id=square3></div>
<div class="square border1 border2"id=square4></div>
<div class="square border2" id=square5></div>
<div class="square" id=square6></div>
<div class="square border1" id=square7></div>
<div class="square" id=square8></div>
<div id=ticTacToeBoard></div>
</div>
</body>
</html>
&#13;
答案 0 :(得分:1)
这是因为每次调用getMarkCount时,都会将markCount设置为0(因为您在getMarkCount中调用了setMarkCount)。只需将getMarkCount替换为markCount。
p = markCount % 2;