js代码如下:
? ? var chars=[];
? ? for(var i=48; i<=57; chars.push(i),i++);
? ? //大写字母存入数组
? ? for(var i=65; i<=90; chars.push(i),i++);
? ? //小写字母存入数组
? ? for(var i=97; i<=122; chars.push(i),i++);
? ? /*从chars中随机获得4个unicode,转为对应字符拼接成4位验证码。返回。*/
? ? function getCode(){
? ? ? var codes=[];
? ? ? //反复执行4次:
? ? ? for(var i=0;i<4;i++){
? ? ? ?// 随机生成0-61之间的一个整数下标
? ? ? ? ? var n=Math.floor(Math.random()*(62));
? ? ? ?//利用随机下标,取出chars数组对应位置的unicode
? ? ? ? ? var unicode=chars[n];
? ? ? ?//将unicode转为字符,push进codes数组
? ? ? ? ? codes.push(String.fromCharCode(unicode));
? ? ?}
? ? ? //循环结束后,将数组中4个元素无缝拼接为字符串返回
? ? ? return codes.join("");
}
?
function login(){
? ? ? ? var input = document.getElementById("check");
? ? ? ? if(getCode().toUpperCase()!=input.value.toUpperCase()){
? ? ? ? ? ? ?return false;
? ? ? ? }
? ? ? ? return true;
}
window.onload = function(){
? ? document.getElementById("checkcode").setAttribute("value","getCode()");
}
html页面如下:
<label for="chech">验证码:</label>
<input type="text" id="check">
<input id="checkcode">
<input type="submit" value="login" onclick="return login()"> /*return取消submit的默认提交行为,后面函数返回为true时,提交,返回为false时不提交*/
原文:http://bri-robby.iteye.com/blog/2260227