Home > Web Front-end > JS Tutorial > Use JavaScript to create random verification codes for web pages

Use JavaScript to create random verification codes for web pages

一个新手
Release: 2017-09-26 10:06:36
Original
2228 people have browsed it

1: getCode.js

/** * 产生随机数的函数 */function validateCode(n){    //验证码可能包含的字符    
var s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";    
var ret=""; //用于保存生成的验证码    //利用循环,随机产生生成验证码的每一个字符    
for(var i=0;i<n;i++) {        
var index = Math.floor(Math.random() * 62); //随机产生一个0~62之间的数字        
ret += s.charAt(index);//将随机产生的数字当作字符串的位置下标,在字符串s中取出该字符,并加入到ret中    }        
return ret; //返回产生的验证码}/* 显示随机数的函数 */function show() {    
document.getElementById("msg").innerHTML=validateCode(4);//在id为msg的对象显示验证码}window.onload=show();//在整个页面加载完成后执行此函数
Copy after login

2:checkCode.html 

<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>制作网页随机验证码</title>
    <script type="text/javascript" src="getCode.js"></script></head><body>
    <span id="msg"></span>
    <input type="button" value="刷新" onclick="show()"></body></html>
Copy after login

The above is the detailed content of Use JavaScript to create random verification codes for web pages. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template