简体   繁体   English

无法弄清楚如何使用javascript中的按钮随机生成数字

[英]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>

Reason : 原因:

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

Corrected : 已更正:

 <!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 : 注意 :

Note that I edited the snippet provided by you. 请注意,我编辑了您提供的代码段。

The following edits were made 进行了以下编辑

  • The script tag was moved at the end of body tag 脚本标签已移动到正文标签的末尾
  • I changed the function and used arrow syntax instead of normal declaration 我更改了功能并使用了箭头语法而不是常规声明
  • Changed Math.floor into bitwise ~~ Math.floor更改为按位~~

Resources : 资源:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM