我已经尝试解决了几个小时,但最终我还是觉得自己像个白痴。这是针对编程类的,代码应该做的是在偶数匝上单击时在框中显示“ x”,在奇数上单击“ o”。现在,单击框时仅显示“ x”。我认为我正在搞砸涉及全局变量的地方。有人可以帮我弄清楚我在做什么错吗?

以下是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>

最佳答案

这是因为每次调用getMarkCount时,都是将markCount设置为0(因为在getMarkCount中调用了setMarkCount)。只需将getMarkCount替换为markCount。

p = markCount % 2;

10-02 00:54