您好,登錄后才能下訂單哦!
使用JavaScript怎么實現一個生成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>
看完上述內容,你們掌握使用JavaScript怎么實現一個生成4位隨機驗證碼功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。