我正在尝试创建一个看起来像健康监测仪的网页,我需要创建一个随机数生成器,作为心脏监测仪。这是我所拥有的:
<?php
function functionName()
{
return rand(5, 15);
}
?>
<html>
<body>
<?php
$i = 0;
while ($i <= 10)
{
echo functionName();
echo "</br>";
$i++;
}
?>
</body>
</html>
问题是数字是一个接一个地打印出来的,我需要它们只出现在同一个地方,但不同。换句话说,如果我有一个部分写着"每秒心跳最佳:",我需要每隔几秒钟出现一个新的数字来代替另一个。
有人知道怎么做吗?我见过类似的事情,所以我很确定这是可行的。
setInterval(function() {
var i = Math.floor(Math.random() * (15 - 5 + 1)) + 5;
document.getElementById("random").innerHTML = i;
}, 1000);
<span id="random"></span>
也许是这样?使用Math.random();和setInterval()
要实现您想要的功能,您可能需要使用JavaScript的JQuery和PHP的组合。对于初学者,创建一个文件randomnumber.php
<?php
die(rand(5,15));
?>
并且,在您的index.php
上
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <!-- load JQuery from Google CDN -->
</head>
<body>
<h2 id="randomNumber"></h2>
</body>
<script>
function getRandom() {
setInterval(function() {
$("#randomNumber").load("randomNumber.php");
}, 3000) // delay in milliseconds
}
getRandom();
</script>
</html>
您可以使用Math.random()
生成随机数。
使用Math.floor()
将一个数字向下舍入为最接近的整数。
并使用setInterval()
以特定的间隔运行函数。
setInterval(function() {
var i = Math.floor(Math.random() * (15 - 5 + 1)) + 5;
document.getElementById("hbeat").innerHTML = 'Heart Beat Per Seconds : ' + i;
}, 1000);
<span id="hbeat"></span>