[英]Javascript Random Number generate
I want to generate random number between 0 to 100 and show a div
tag if that random isn't less than 10. I have this code but it doesn't work, please can you help me fix the error. 我想生成0到100之间的随机数,并显示一个div
标签,如果该随机不小于10.我有这个代码,但它不起作用,请你帮我修复错误。
I have already tried on google but I can not find code for php 我已经尝试过谷歌,但我找不到PHP的代码
function showbox(){ document.getElementById("ap1").style.visibility = "visible"; } function myFunction(name) { var x = document.getElementById("demo") x.innerHTML = Math.floor((Math.random() * 100) + 1); } if(myFunction(<=10){ setTimeout(showbox, 35000); }
<div id="ap1" style="visibility: hidden;"></div>
Your code has SyntaxError
. 您的代码具有SyntaxError
。 You can use this code 您可以使用此代码
var element = document.getElementById("ap1"); var random = Math.floor((Math.random() * 100) + 1); element.innerHTML = random; if (random >= 10){ document.getElementById("ap1").style.visibility = "visible"; } else console.log(random);
<div id="ap1" style="visibility: hidden;"></div>
Math.floor((Math.random() * 100) + 1)
generate number between 1 and 100
. Math.floor((Math.random() * 100) + 1)
生成1 and 100
之间的数字。 If you want to generate number between 0 and 100
use Math.floor((Math.random() * 101))
or Math.round((Math.random() * 100))
如果要生成0 and 100
之间的数字,请使用Math.floor((Math.random() * 101))
或Math.round((Math.random() * 100))
Try this . 试试这个 。 The code wasn't correct. 代码不正确。 You used demo
id but you have ap1
, and the if
condition also was wrong in JavaScript. 您使用了demo
ID但是您有ap1
,而且if
条件在JavaScript中也是错误的。
The JavaScript code: JavaScript代码:
function myFunction(name) {
var x = document.getElementById("ap1")
var randomNum = Math.floor((Math.random() * 100) + 1);
if (randomNum > 10) {
x.innerHTML = randomNum;
} else {
x.innerHTML = 'empty';
}
}
setTimeout(myFunction, 350);
you need to close myFunction
in the if
and you need to return
in myFunction
:- 你需要在if
关闭myFunction
,你需要在myFunction
return
: -
function showbox(){ document.getElementById("ap1").style.visibility = "visible"; } function myFunction(name) { var x = document.getElementById("ap1") return x.innerHTML = Math.floor((Math.random() * 100) + 1); } if(myFunction() <= 10){ setTimeout(showbox, 35000); }
<div id="ap1" style="visibility: hidden;"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.