所以我对所有的编码都是全新的,我对此非常可怕!我试图创建一个简单的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()"> </button>
<button id="mybtn2" onclick="myFunction2()"> </button>
<button id="mybtn3" onclick="myFunction3()"> </button>
<p style="clear:both"></p>
<button id="mybtn4" onclick="myFunction1()"> </button>
<button id="mybtn5" onclick="myFunction2()"> </button>
<button id="mybtn6" onclick="myFunction3()"> </button>
<p style="clear:both"></p>
<button id="mybtn7" onclick="myFunction1()"> </button>
<button id="mybtn8" onclick="myFunction2()"> </button>
<button id="mybtn9" onclick="myFunction3()"> </button>
<p></p>
<script>
var X= document.getElementById("mybtn1").innerHTML;
function myFunction1() {
//var X= document.getElementById("mybtn1").innerHTML;
if (X == " ") {
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 == " ") {
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 == " ") {
document.getElementById("mybtn3").innerHTML = X;
}
if (X == "X") {
document.getElementById("mybtn3").innerHTML = "O";
}
if (X == "O") {
document.getElementById("mybtn3").innerHTML = "X";
}
}
</script>
</body>
</html>
答案 0 :(得分:2)
你可以试试这个:
var btn = document.getElementById("mybtn1");
btn.innerHTML = btn.innerHTML === "X" ? "O" : "X";
或者简单地说:
<button onclick="switchIt(this)"> </button>//An example of button
和
function switchIt(btn) {
btn.innerHTML = btn.innerHTML === "X" ? "O" : "X";
}