有没有一种方法可以确保刷新页面后变量不会更改?

时间:2019-05-13 22:51:34

标签: javascript math

我正在使用随机生成的数字进行数字猜谜游戏,但是当您猜测数字时,我希望它保持不变,直到正确猜出数字为止。这是代码的样子,我不明白为什么每次猜测后数字都会变化。

<!DOCTYPE html> 
<html> 
<head> 
<title>Number Guessing Game</title> 

</head> 

<body> 
<h1>Guess The Number</h1> 

<p>A number has been randomly generated from 1- 50. Please try and     guess the number.</p> 

<form> 
<label for="guessField">Enter a guess: </label> 
<input type = "text" id = "guessField" class = "guessField"> 
<input type = "submit" value = "Submit guess"
    class = "guessSubmit" id = "submitguess"> 
</form> 

<script> 
// for some reason a new random number is generated after every guess
const randomnumber = Math.floor(Math.random()*50) +1;  

var guess = 0; 

document.getElementById("submitguess").onclick = function(){ 

var userguess = document.getElementById("guessField").value; 

if(userguess<1||userguess>50||isNaN(userguess)){
guess+=1;
alert("That is not a valid guess.")
}

else if(userguess == randomnumber) 
{    
alert("You got it in "
        + guess + " guess(es) "); 
} 
else if(userguess > randomnumber) 
{    
guess+= 1; 
alert("That guess is too high. Try again!"); 
} 
else 
{ 
guess+=1; 
alert("That guess is too low. Try again!") 
} 
} 

//this shows that it changes after every guess 
document.write(randomnumber)
</script> 

</body> 
</html>

2 个答案:

答案 0 :(得分:0)

<input type="submit" .. >更改为<button type="button" .. >。 提交按钮正在提交页面并导致重新加载。

答案 1 :(得分:0)

替换

<input type="submit" value="Submit guess" class="guessSubmit" id="submitguess">

使用

<button type="button" class="guessSubmit" id="submitguess">Submit guess</button>

因此,单击按钮时您不会收到表单提交的信息(因此,页面重新加载会重置所有Javascript)。

接下来,您需要将该输入字段的值强制转换为Number(输入字段值始终为 字符串),以便与数字进行比较:

var userguess = parseInt(document.getElementById("guessField").value);