我正在尝试使用表单制作随机数生成器。当您按下按钮并输入最大数字时,它会出现一个显示 NaN 的对话框,此时它意味着会产生随机数。
我有一些代码,如下所示:
<html>
<head>
</head>
<body>
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button name="generate" type="submit" onclick="gennum()">Generate!</button>
<script>
function gennum()
{
alert(Math.floor(Math.random() * num.value + 1));
}
var num = document.getElementById('numgen').value;
</script>
</form>
</body>
</html>
我不太擅长Javascript,但我知道一点。如果有人知道如何解决这个问题,我会很高兴。
最佳答案
num.value
是一个字符串。使用 parseInt(num.value, 10)
将其转换为数字,这样就可以适本地与数字相加。
此外,您似乎获得了该值两次,第一次是在页面加载时(因此它还没有值:
var numElem = document.getElementById('numgen'); //remove value here
然后在你的函数中:
alert(Math.floor(Math.random() * parseInt(num.value + 1)));
并且,您需要在按钮上使用 type="button"
,否则页面将重新加载。
这是使用更好的实践重构的代码。
标记:
<form name="gen">
<h1>Random Number Generator</h1>
<b>Number:</b> 1 to
<input id="numgen" type="text"/>
<button id="generate" type="button">Generate</button>
</form>
JavaScript:
/* get element references */
var genButton = document.getElementById('generate');
var numInput = document.getElementById('numgen');
//use javascript to add the click function
genButton.addEventListener('click', function() {
/* it's easier to read and debug if you break things up
* instead of putting it all on one line with tons of ((()))
*/
var rand = genRandom(1, parseInt(numInput.value, 10));
alert(rand);
});
function genRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
关于Javascript 随机数生成器出现 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20456918/