获取随机数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>验证码</title> </head> <style> #txt{ width:120px; height:40px; border:1px solid #aaa; margin-top: 20px; } </style> <body> <button id="btn">获得验证码</button> <div class="txt" id="txt"></div> </body> <script src="js/jquery-1.4.2.min.js"></script> <script> window.onload = function(){ var oBtn = document.querySelector('#btn'); var oTxt = document.querySelector('#txt'); //生成随机数 function rund(n,m){ return Math.floor(Math.random()*(m-n)+n); } //去除数组相同的数字 function findArr(n,arr){ for(var i=0;i<arr.length;i++){ if(arr[i] == n){ return true; }else{ return false; } } } oBtn.onclick = function(){ //每次单击实现一次 var num = []; while(num.length < 6){ var m = rund(0,9); if(!findArr(m,num)){ num.push(m); } } var str = num.splice('') num = str.join(); oTxt.innerHTML = num; } } </script> </html>