猜数字游戏:页面加载生成随机数,为何每次猜数变量仍刷新?
Hey there! Let's break down what's going on here and get your game working like you want it to 😊
The Core Issue: Page Refreshing Resets Your Random Number
Your initial thought is totally correct—code inside the <script> tag does only run once when the page loads. The reason your random number keeps changing every time you click "Guess" is because your button is a default form submit button. When you click it, the browser automatically submits the form, which triggers a full page refresh. This means the entire script runs again, generating a new random number each time. The console logs you're seeing are from the refreshed page, not the original one!
How to Fix It
We just need to stop the form from refreshing the page, and your initial random number will stay fixed across multiple guesses. Here's the updated code:
<p>Guess a number</p> <form> <input type="text" id="guess"> <button id="guessbutton">Guess</button> </form> <script type="text/javascript"> // Generate the secret number ONCE when the page loads var numberwang = Math.floor(Math.random() * 6); console.log("Secret number (shhh):", numberwang); document.getElementById("guessbutton").onclick = function(e) { // Critical: Prevent the form from submitting and refreshing the page e.preventDefault(); const userGuess = document.getElementById("guess").value; if (userGuess == numberwang) { alert("That's numberwang!") // Optional: Uncomment below if you want to generate a new number after a win // numberwang = Math.floor(Math.random() * 6); // console.log("New secret number:", numberwang); } else { alert("That's not numberwang, try again") } } </script>
Key Changes Explained
e.preventDefault(): This tells the browser to skip its default behavior (submitting the form and refreshing the page). Now your page stays put, and the originalnumberwangvalue remains intact.- The random number is still generated once when the page loads—you didn't need to change that part! The problem was never the variable itself, just the page resetting every time you clicked the button.
Bonus Optimization
To make your code a little cleaner and more efficient, you can grab your DOM elements once when the page loads instead of querying them every time you click:
// Get elements once at page load const guessInput = document.getElementById("guess"); const guessButton = document.getElementById("guessbutton"); var numberwang = Math.floor(Math.random() * 6); console.log("Secret number (shhh):", numberwang); guessButton.onclick = function(e) { e.preventDefault(); const userGuess = guessInput.value; // Rest of your logic here... }
内容的提问来源于stack exchange,提问作者John Sonnino

