随机产生一个四位数字的验证码

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      span {
        display: inline-block;
        padding: 6px;
        background-color: #ddd;
        letter-spacing: 2px;
      }
    </style>
  </head>
  <body>
    <span id="s"></span>
    <button id="btn">刷新验证码</button>
    <script>
      // 函数功能 随机生成4位数字验证码
      function code(n) {
        n = n || 4;
        var res = "";
        for (var i = 0; i < n; i++) {
          var n1 = rand(0, 9);
          res += n1;
        }
        return res;
      }

      // document.write(code())
      $("s").innerHTML = code();

      $("btn").onclick = function () {
        $("s").innerHTML = code();
      };

      function rand(min, max) {
        return min + parseInt(Math.random() * (max - min + 1));
      }
      function $(id) {
        return document.getElementById(id);
      }
    </script>
  </body>
</html>
posted @ 2021-03-28 19:57  干饭吧  阅读(253)  评论(0)    收藏  举报