JavaScript点击按钮生成4位随机验证码

本文实例为大家分享了js实现点击按钮生成4位随机验证码的具体代码,供大家参考,具体内容如下

效果图:

代码:

<!DOCTYPE html>
<html lang="en">
 
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
 div {
  width: 100px;
  height: 50px;
  background: red;
  text-align: center;
  line-height: 50px;
 }
 </style>
</head>
 
<body>
 <div id="yzm"></div>
 <button id="btn">点击生成验证码</button>
 <script>
 // var str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
 //数组转换为字符串
 // var arr = str.split("");
 
 var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
 // console.log(arr);
 //页面刚加载时候调用它
 sjs(arr);
 
 btn.onclick = function() {
  sjs(arr);
 }
 
 function sjs(arr) {
  var code = Math.floor(Math.random() * arr.length);
  var code1 = Math.floor(Math.random() * arr.length);
  var code2 = Math.floor(Math.random() * arr.length);
  var code3 = Math.floor(Math.random() * arr.length);
  var n = arr[code] + arr[code1] + arr[code2] + arr[code3];
  yzm.innerHTML = n
 }
 </script>
</body>
 
</html>

小编再为大家分享一段代码:点击产生四位随机数字母与数字

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>点击产生随机数</title>
  <style>
  span{
    display: block;
    width: 110px;
    height: 50px;
    border: 1px solid red;
    text-align: center;
    line-height: 50px;
  }
  </style>
</head>
<body>
  <span id="demo" onclick="init();"></span>
  <script>
    init();
    function init(){
    var arr=[];
    for(var i=48;i<123;i++){
     if(i>57 && i<65) continue;
     if(i>90 && i<97) continue;
     arr.push(String.fromCharCode(i));
    }
    arr.sort(function () {
     return Math.random()-0.5;
    });
    arr.length=4;
    
    var span= document.getElementById('demo');
    span.textContent=(arr.join(""));
        }
  
  </script>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持鸟哥教程(niaoge.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#niaoge.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。