gpt4 book ai didi

javascript - 如何在页面加载时生成随机数?

转载 作者:搜寻专家 更新时间:2023-10-31 22:36:24 25 4
gpt4 key购买 nike

我试图在页面加载时生成一个随机数,但由于某种原因它似乎不起作用。每次用户按下提交按钮时,随机数都会不断生成,而不是从页面加载开始就生成一次。

我的 HTML:

<!DOCTYPE html>
<html>
<head>
<title> How many fingers </title>
<script type="text/javascript" src="main.js"> </script>
</head>

<body>
<h1> Test your luck </h1>
<h2> How many fingers do I have?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()"> submit </button>
</body>
</html>

我的 JavaScript:

function loadNumber(){
var myNumber = (Math.floor(Math.random()*10) +1);
}
//am not sure if the above function should generate the random number!
window.onload = loadNumber;

function check(){

var numberOfGuesses = (Math.floor(Math.random()*9)+1);
var guess = document.getElementById("myGuess").value;
var number = (Math.floor(Math.random()*10) +1);

if(guess==number){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
}else{
numberOfGuesses++;
alert("nope, try again!")
}
}

最佳答案

我真的很困惑你的代码。因此,我对其进行了重组,将 myNumber 和 numberOfGuesses 置于函数之外,以扩大范围。在页面加载时,它会在 loadNumber() 中生成随机数,它位于此处的根范围内。然后检查是否可以访问该内容并增加猜测。

var myNumber;
var numberOfGuesses = 0;

function loadNumber(){
myNumber = (Math.floor(Math.random()*10) +1);
}

function check(){
numberOfGuesses++;

var guess = document.getElementById("myGuess").value;

if(guess==myNumber){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
} else {
alert("nope, try again!")
}

}

window.onload = loadNumber;

关于javascript - 如何在页面加载时生成随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com