[英]Can't figure out how to randomly generate numbers with a button in javascript
followed a tutorial just with different layout and names and still can't seem to find whats wrong? 跟随了一个教程,只是其布局和名称不同,而似乎仍然找不到问题所在?
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = math.floor((math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>
What you are doing wrong is that you are using math
instead of Math
. 您做错了是您使用的是
math
而不是Math
。 JavaScript is case sensitive and Math
is defined while math
is not. JavaScript区分大小写,而
Math
则不定义math
。
<!DOCTYPE html> <html> <head> </head> <body> <button onclick="myrandom()">Generate</button> <p id='rand'></p> <script> var myrandom = () => { var x = ~~((Math.random() * 10) + 1); document.getElementById("rand").innerHTML = x; } </script> </body> </html>
Also please note that it is better that you write the JS code at the end of the body tag and the script tag is the last one in the body tag. 另外请注意,最好在body标签的末尾编写JS代码,而script标签是body标签的最后一个。
Note that I edited the snippet provided by you. 请注意,我编辑了您提供的代码段。
The following edits were made 进行了以下编辑
Math.floor
into bitwise ~~
Math.floor
更改为按位~~
You have a typo, You need to capitalize the first letter of math -> Math . 您有一个错字,您需要将math的首字母大写-> Math 。
<!DOCTYPE html> <html> <head> <script> function myrandom() { var x = Math.floor((Math.random() * 10) + 1); document.getElementById("rand").innerHTML = x; } </script> </head> <body> <button onclick="myrandom()">Generate</button> <p id='rand'></p> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.