试图在点击按钮时获得一个随机数

trying to get a random number on button click

本文关键字:随机数 一个 按钮      更新时间:2024-06-24

我试图使用javascript获取一个0-20范围内的随机数,以便在用户单击按钮后显示在文本框中,但到目前为止我没有成功。我的代码中有什么错误?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<form><input name="code" id="code" type="text" value="" >
<script type="text/javascript">
    function makeid()
    {
    var randomnumber=Math.floor(Math.random() * 20)
}
</script>
<input type="button" style="font-size:9pt" value="Generate Code" onclick="document.getElementById('code').value = makeid()">
</input>
</form>
</body>
</html>

函数需要返回一个值:

function makeid() {
    return Math.floor(Math.random() * 20)
}

函数不返回值,这就是为什么将输入设置为undefined的原因。

试试这个:

function makeid() {
    return Math.floor(Math.random() * 20);
}