今日学习了验证码的生成与检验,逻辑为:
1.加载页面时自动随机生成数字验证码。
2.点击看不清,更换验证码重新生成验证码。
3.点击确定按钮检验输入框内的值与验证码是否相等,不相等时弹出警告并清空输入框和刷新验证码。
代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>验证码</title><style>#checkcode{background-color:lightgray;color: blue;font-size: 30px;}#renew{color: blue;text-decoration:underline;cursor:pointer; }</style>
</head>
<body><div><span id="checkcode">858158</span><a id="renew">看不清,换一张</a></div><div><p>验证码:<input type="text" id="inputcode"></p><button id="check">确定</button></div><script>//加载时生成验证码window.onload=function(){var res=getcode();function getcode(){var arr=['0','1','2','3','4','5','6','7','8','9']var str='';for(var i=0;i<6;i++){var num=Math.round(Math.random()*(9-0)+0);str += arr[num];}return str;}document.getElementById('checkcode').innerText=res;//点击生成验证码document.getElementById('renew').onclick=function(){document.getElementById('checkcode').innerText=getcode();}//点击确定检验验证码document.getElementById('check').onclick=function(){var code=document.getElementById('checkcode').innerText;var inputcode=document.getElementById('inputcode').value;if(code != inputcode){alert("您输入的验证码不正确");document.getElementById('inputcode').value=''document.getElementById('checkcode').innerText=getcode();return false;}}}</script>
</body>
</html>
显示效果为:




















