HTML 页面随机输出指定数字 - 代码示例
要在 HTML 页面上添加一个输出框,并且每次访问时随机输出指定的数字,可以使用以下代码:
<!DOCTYPE html>
<html>
<head>
<title>随机输出指定数字</title>
<script>
function randomOutput() {
// 创建一个数组,包含指定的数字
var numbers = [123, 1456, 4634];
// 从数组中随机选择一个数字
var randomIndex = Math.floor(Math.random() * numbers.length);
var randomNum = numbers[randomIndex];
// 将选中的数字输出到文本框
document.getElementById('output').value = randomNum;
}
</script>
</head>
<body onload='randomOutput()'>
<h1>随机输出指定数字</h1>
<input type='text' id='output' readonly>
</body>
</html>
在这个示例中,我们创建了一个包含指定数字的数组。然后,通过Math.random()函数生成一个随机的数组索引,使用Math.floor()函数将其转换为整数值。然后,我们从数组中选择对应索引的数字,并将其输出到具有 id 为output的文本框中。
在<body>标签的onload属性中调用randomOutput()函数,以便在页面加载时随机输出一个数字。
原文地址: https://www.cveoy.top/t/topic/qnt2 著作权归作者所有。请勿转载和采集!