jquery 验证码效果代码实例

快乐打工仔 分类:实例代码

分享一段代码实例,它利用jquery实现了简单的验证码效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<style type="text/css">
body {
  padding: 0;
  margin: 0;
}
ul {
  padding: 0;
  margin: 0;
}
.box {
  width: 600px;
  height: auto;
  margin: 0 auto;
}
.box > div {
  margin-top: 15px;
  font-size: 18px;
}
.box .code-box .code {
  font-size: 22px;
  color: #f00;
}
.box .code-box .huan {
  font-size: 18px;
  cursor: pointer;
}
.box .input input {
  width: 200px;
  height: 28px;
}
.button {
  text-align: center;
  width: 80px;
  height: 30px;
  background: #FF3333;
  line-height: 30px;
  color: #fff;
  cursor: pointer;
  border-radius: 5px;
}
.change {
  color: #f00;
  font-size: 16px;
  display: none;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<script>
$(function() {
  $(".huan").on("click", createCode)
  createCode();
})
var code;
 
function createCode() {
  var selectChar = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
  code = '';
  var codeLength = 5;
  var codeContent = $(".code");
  for (var index = 0; index < codeLength; index++) {
    var charIndex = Math.floor(Math.random() * selectChar.length);
    //alert(charIndex)
    code += selectChar[charIndex];
    codeContent.html(code);
  }
}
 
$(".button").on("click", function() {
  var Code = $("#code").val();
  if (Code.length <= 0) {
    $(".change").show();
  } else if (Code != code) {
    $(".change").show().html("验证码有误");
    createCode();
  } else {
    $(".change").html("验证码正确");
  }
})
</script>
</head>
<body>
  <div class="box">
    <div class="code-box">
      <span>验证码</span>
      <span class="code"></span>
      <span class="huan">换一张</span>
    </div>
    <div class="input">
      <span>输入验证码</span>
      <input type="text" id="code" placeholder="输入验证码">
      <span class="change">验证码为空</span>
    </div>
    <div class="button">提交</div>
  </div>
</body>
</html>

上面的代码实现了我们的要求,下面介绍一下它的实现过程。

一.代码注释:

(1).$(function() {}),当文档结构完全加载完毕再去执行函数中的代码。

(2).$(".huan").on("click", createCode),为class属性值为huan的元素注册click事件处理函数,点击即可实现刷新验证码。

(3).createCode(),页面加载完毕就会显示验证码。

(4).var code,声明一个变量,用来存储验证码字符串。

(5).function createCode() {},实现生成验证码功能。

(6).var selectChar = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),创建一个数组,数组的元素用来组成验证码,可以自己再添加更多。

(7).code = '',将验证码字符串清空,防止下一次生成叠加。

(8).var codeLength = 5,验证码的长度。

(9).var codeContent = $(".code"),获取对应的元素对象。

(10).for (var index = 0; index < codeLength; index++) {

  var charIndex = Math.floor(Math.random() * selectChar.length);

  code += selectChar[charIndex];

  codeContent.html(code);

},通过循环方式生成指定长度的验证码。

二.相关阅读:

(1).Math.floor()可以参阅javascript Math.floor()一章节。

(2).Math.random()可以参阅javascript Math.random()一章节。

jquery 验证码效果代码实例,这样的场景在实际项目中还是用的比较多的,关于jquery 验证码效果代码实例就介绍到这了。

jquery 验证码效果代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容