<style> div{width:100px;height:50px;border:1px solid #000;text-align:center;line-height:50px;} </style> <button id="btn1" onclick = "fn1()">隨機生成驗證碼</button> <div id = "fn1"></div>
//幾個常見字母的ASCII碼大小: 「A」爲65;「a」爲97;「0」爲 48;
var oBtn1 = document.getElementById('btn1'); var oFn1 = document.getElementById('fn1'); var fn1 = function(){ var arr = []; //建立空數組,放入a~Z 0~9 for(var i=65;i<=90;arr.push(i),i++){} //a~z for(var j=97;j<=122;arr.push(j),j++){}//A~Z for(var k=48;k<=57;arr.push(k),k++){}//0~9 var arr2 = []; for(var i=0;i<4;i++) { //從0-61之間取隨機數 var index = Math.floor(Math.random() * 62); //返回 0 至 61 之間的數 var char = String.fromCharCode(arr[index]);//轉換ASCII碼 arr2.push(char); } var str1 = arr2.toString(); //數組轉換字符串 var str2 = X.replace(/,/g, ""); oFn1.innerHTML = str2; }