验证码在生活中很常见,所以做了个验证码案例:
感觉蛮简单的,就不解释了,代码里有注释,如下:
var span = document.getElementsByTagName('span')[0];
var a = document.getElementsByTagName('a')[0];
var input = document.getElementsByTagName('input')[0];
var btn = document.getElementsByTagName('button')[0];
var code = "";
//生成验证码
function createCode(){
code="";
var codelength = 6; //设置验证码位数;
//设置验证码生成数组,验证码从中取直;
var codeArr = new Array(0,1,2,3,4,5,6,7,8,9,'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');
//随机获取验证码数组下标,生成验证码
for(var i=0; i<codelength; i++){
code += codeArr[Math.floor(Math.random()*codeArr.length)];
}
span.innerText = code;
return code;
}
//cresteCode();
window.onload = function(){
createCode();
}
a.onclick = function(){
createCode();
return false;
}
btn.onclick = function(){
if(input.value == ""){
alert("验证码为空,请输入验证码!");
}else if(input.value.toLocaleUpperCase() == code.toLocaleUpperCase()){
alert("验证码输入正确!");
}else {
alert("验证码输入错误,请重新输入验证码!");
createCode();
}
}
html:
<div id="wrap">
<div id="code">
<span></span>
<a href="">看不清楚换一个</a>
</div>
<div id="checkcode">
<ul>
<li>请输入验证码:<input type="text"></li>
<li><button>验证</button></li>
</div>
</div>