本文實例為大家分享了JavaScript生成4位隨機驗證碼的具體代碼,供大家參考,具體內容如下
代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
<!doctype html> < html > < head > < meta charset = "utf-8" > < title >4位隨機驗證碼的生成</ title > < style > label{ color:aqua; float:left; font-size: 20px; line-height:2em; } #tex{ display:inline-block; width:50px; height: 25px; float:left; text-align: center; font-size:15px; margin-top:10px; } #showyz{ border:3px solid green; color:blue; width:90px; height:40px; text-align:center; float:left; margin-left:15px; line-height: 2.5em; } #hyz{ background-color:burlywood; border:1px solid burlywood; width:50px; height:20px; float: left; margin-left:20px; margin-top: 10px; margin-right:15px; } #btn{ } </ style > </ head > < body > < label for = "tex" >請輸入驗證碼:</ label >< input type = "text" id = "tex" maxlength = "4" autofocus> < div id = "showyz" ></ div > < div id = "hyz" >換一張</ div >< br > < input type = "button" id = "btn" value = "確認" > </ body > < script > //定義個空數組保存62個編碼 var codes=[]; //將數字對應的編碼保存到codes數組中,數字編碼范圍【48-57】 for(var i=48;i<=57;i++){ codes.push(i); } //將大寫字母對應的編碼保存到codes數組中,對應編碼范圍【65-90】 for(var i=65;i<=90;i++){ codes.push(i); } //將小寫字母對應的編碼保存到codes數組中,對應編碼范圍【97-122】 for(var i=97;i<=122;i++){ codes.push(i); } //定義個方法生成62位隨機數作為數組角標返回隨機的編碼,再將其編碼轉化為對應數字或者字母 function suiji(){ var arr=[];//定義個數組保存4位隨機數 for(var i=0;i< 4 ;i++){ var index = Math .floor(Math.random()*(61-0+1)+0);//生成個隨機數 var char = String .fromCharCode(codes[index]);//解碼 arr.push(char); //存入到數組arr中 } return arr.join("");//將數組轉為字符串,以空格分隔,并返回 } var yzm = suiji ();//調用方法,將放回的驗證碼返回到yzm中 //獲取上述元素 var tex = document .getElementById("tex"); var showyz = document .getElementById("showyz"); var hyz = document .getElementById("hyz"); var btn = document .getElementById("btn"); //將驗證碼寫入到id為showyz的div中 showyz.innerHTML = yzm ; //實現換一張驗證碼功能 hyz.ο nclick = function (){ yzm = suiji (); showyz.innerHTML = yzm ; } //將自己輸入的驗證碼與獲取的隨機驗證碼驗證 btn.ο nclick = function (){ var textvalue =tex.value;//獲取輸入的值 if(textvalue.toLowerCase()==yzm.toLowerCase()){//將值都轉為小寫比較 alert("驗證碼輸入正確!"); yzm = suiji (); showyz.innerHTML = yzm ; tex.value = "" ; } else{ alert("驗證碼輸入錯誤,請重新輸入!"); yzm = suiji (); showyz.innerHTML = yzm ; tex.value = "" ; } } </script> </ html > |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_42026831/article/details/80042654