简单的Tic Tac Toe与javascript

时间:2016-07-11 01:55:44

标签: javascript html tic-tac-toe

所以我对所有的编码都是全新的,我对此非常可怕!我试图创建一个简单的tic tac toe board,我需要一个按钮,根据前一个按钮显示的内容显示X或O.如何让它返回上一个按钮?这是我到目前为止所做的,它应该是超级简单的。有没有人可以指出我正确的方向?

<!DOCTYPE html>
<html>
<head>
<title> Project 8 </title>
</head>
<body>
<p>Click the button once to change its value</p>

<button id="mybtn1" onclick="myFunction1()">&nbsp;</button>
<button id="mybtn2" onclick="myFunction2()">&nbsp;</button>
<button id="mybtn3" onclick="myFunction3()">&nbsp;</button>
<p style="clear:both"></p>
<button id="mybtn4" onclick="myFunction1()">&nbsp;</button>
<button id="mybtn5" onclick="myFunction2()">&nbsp;</button>
<button id="mybtn6" onclick="myFunction3()">&nbsp;</button>
<p style="clear:both"></p>
<button id="mybtn7" onclick="myFunction1()">&nbsp;</button>
<button id="mybtn8" onclick="myFunction2()">&nbsp;</button>
<button id="mybtn9" onclick="myFunction3()">&nbsp;</button>

<p></p>

<script>

    var X= document.getElementById("mybtn1").innerHTML;

function myFunction1() {
    //var X= document.getElementById("mybtn1").innerHTML;
    if (X == "&nbsp;") {
        document.getElementById("mybtn1").innerHTML = "X";
    }
    else (X == "X") {
    document.getElementById("mybtn1").innerHTML = "O";
    }
    else if (X == "O") {
    document.getElementById("mybtn1").innerHTML = "X";
    } 
}

function myFunction2() {
    //var X= document.getElementById("mybtn2").innerHTML;
    if (X == "&nbsp;") {
        X="X"
        document.getElementById("mybtn2").innerHTML = X;
    }
    if (X == "X") {
    document.getElementById("mybtn2").innerHTML = "O";
    } 
    if (X == "O") {
    document.getElementById("mybtn2").innerHTML = "X";
    } 
}

function myFunction3() {
    //var X= document.getElementById("mybtn3").innerHTML;
    if (X == "&nbsp;") {
        document.getElementById("mybtn3").innerHTML = X;
    }
    if (X == "X") {
    document.getElementById("mybtn3").innerHTML = "O";
    } 
    if (X == "O") {
    document.getElementById("mybtn3").innerHTML = "X";
    } 
}
</script>


</body>
</html>

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

var btn = document.getElementById("mybtn1");
btn.innerHTML = btn.innerHTML === "X" ? "O" : "X";

或者简单地说:

<button onclick="switchIt(this)">&nbsp;</button>//An example of button

function switchIt(btn) {
    btn.innerHTML = btn.innerHTML === "X" ? "O" : "X";
}

演示: https://jsfiddle.net/iRbouh/6qn9Lz9u/1/