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

时间:2012-08-01 03:14:54

标签: javascript html

我正在尝试使用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>

2 个答案:

答案 0 :(得分:1)

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

请改为尝试:

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

答案 1 :(得分:1)

你的职能需要返回一个值:

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