我是全新的JavaScript和HTML,所以我希望有人可以偷看我的代碼,並告訴我爲什麼某些語法不工作。在下面的代碼中,我使用document.getElementById來檢索每次想要處理的元素。我將它們聲明爲gameTime()中的局部變量,並在整個函數中使用它。Javascript猜測遊戲
var randNum = Math.floor(100*Math.random()) +1;
var numGuesses = 0;
function gameTime()
{
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
document.getElementById("guess").value = "";
}
function reset()
{
randNum = Math.floor(100*Math.random()) +1;
numGuesses = 0;
document.getElementById("guess").value = "";
document.getElementById("status").value = "";
}
function quit()
{
document.getElementById("status").value += ("The correct number was " + randNum + "!\r")
}
然後,我通過全球範圍內聲明兩個元素,並在每它似乎並沒有在所有的工作,我只是不明白爲什麼函數中使用它試了一下。
var randNum = Math.floor(100*Math.random()) +1;
var numGuesses = 0;
var guess = document.getElementById("guess").value;
var status = document.getElementById("status");
function gameTime()
{
numGuesses++;
if(guess == "")
{
alert("You did not guess a number!")
numGuesses--;
}
else if(guess == randNum)
status.value += (guess + " was the right number! It only took you " + numGuesses + " tries" + "\r")
else if(guess > randNum)
status.value += (guess + " is too high!" + "\r")
else
status.value += (guess + " is too low!" + "\r")
guess.value = "";
}
function reset()
{
randNum = Math.floor(100*Math.random()) +1;
numGuesses = 0;
guess.value = "";
status.value = "";
}
function quit()
{
status.value += ("The correct number was " + randNum + "!\r")
}
這裏還有伴隨這些js文件guess.js是第一個代碼塊的HTML文件,guessAgain.js是第二個代碼塊。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" src="guessAgain.js"></script>
</head>
<body>
<label for = "guess"> Your Guess: </label>
<input type = "text" id = "guess" value = "" />
<input type = "button" onclick = "gameTime()" value = "Submit" />
<input type = "button" onclick = "reset()" value = "New Game" />
<input type = "button" onclick = "quit()" value = "Quit" />
<br>
<textarea id = "status" rows = "10" cols = "52"></textarea>
</body>
</html>
感謝您的任何見解,你可以給我。
你可以考慮提供一個http://jsfiddle.com,以便人們可以輕鬆地嘗試上面的代碼/程序。 – 2012-08-04 17:46:06