当前位置:   article > 正文

生成4位大写字母的随机 验证码_在页面上随机生成四位存大写字母的验证码

在页面上随机生成四位存大写字母的验证码

 场景题:页面上有一个按钮,点击时在后面显示出一个由4位大写字母组成的随机字符串。(考点:Math方法、字符串下标、点击事件、文本内容操作)

 

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <button>点击</button><span></span>
  11. <script>
  12. let btn = document.querySelector("button");
  13. let span = document.querySelector("span");
  14. // 获取26位大写字母
  15. let arr = [];
  16. for (let i = 0; i < 26; i++) {
  17. arr.push(String.fromCharCode(65 + i));//Unicode编码
  18. }
  19. let index;//存储索引位置
  20. btn.addEventListener("click", function () {
  21. span.textContent = "";
  22. // 获取4个大写字母
  23. for (let i = 0; i < 4; i++) {
  24. index = getRandom(0, arr.length - 1);
  25. // 使用字符拼接的方式输出到span标签之间
  26. span.textContent += arr[index];
  27. }
  28. })
  29. // 获取随机索引
  30. function getRandom(min, max) {
  31. return Math.floor(Math.random() * (max - min + 1) + min);
  32. }
  33. </script>
  34. </body>
  35. </html>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/54619
推荐阅读
相关标签
  

闽ICP备14008679号