xqlee 1003 0 2017-07-02 21:44:26

文章位置:左搜> 编程技术> 正文
Jquery cookie插件实现点击获取验证码后60秒内禁止重新获取,可直接拿走用
注意:本例子依赖一下库
1.jQuery
2.jQuery cookie
可根据自身环境进行修改

代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>验证码获取按钮防止刷新</title>
<link rel="stylesheet" type="text/css" href="../libs/bootstrap/bootstrap-3.3.7/css/bootstrap.css">
<style type="text/css">
.content{
	margin: 20px 0px 0px 20px;
}
</style>
</head>
<body>
<div class="form-inline content">
<h1>验证码获取按钮防止刷新</h1>
<div class="alert alert-info base64-de-out">
注意:<br>
1.本案例依赖jQuery;<br>
2.本案例依赖jQuery的cookie插件<br>
</div>
<input type="text" class="form-control" placeholder="请输入邮箱地址"><button class="btn btn-default test-btn">获取验证码</button>
</div>

<script type="text/javascript" src="../libs/jQuery/jquery.js"></script>
<script type="text/javascript" src="../libs/jQuery/plugins/cookie/jquery.cookie.js"></script>
<script type="text/javascript" src="../libs/bootstrap/bootstrap-3.3.7/js/bootstrap.js"></script>
<script type="text/javascript">

$(function(){
	var btn=$('.test-btn');
	//1.默认检测验证码按钮
	checkResendCode(btn);
	//2.绑定点击事件
	$(btn).click(function(){
		//do somthing
		//code ....
		
		//设置按钮状态
		resendCode(this);
	});
})

/**检查cookie中的验证码统计是否存在***/
function checkResendCode(btnObject)
{
	if($.cookie('captchaCount')){
		var count=$.cookie('captchaCount');
		//设置按钮的显示和不可用状态
		$(btnObject).html(count+'秒重新获取').attr('disabled',true);
		var resend=setInterval(function(){
            if (count > 0){
            	$(btnObject).html(count+'秒重新获取').attr('disabled',true).css('cursor','not-allowed');
                $.cookie("captchaCount", count, {path: '/', expires: (1/86400)*count});
            }else {
                clearInterval(resend);
                btn.html("获取验证码").attr('disabled',false);
            }
            count--;
		},1000);
	}
}
/**重新发送事件***/
function resendCode(btnObject)
{
	var count=60;
	var resend = setInterval(function(){
	       if (count > 0){
	    	   $(btnObject).html(count+"秒重新获取");
	           $.cookie("captchaCount", count, {path: '/', expires: (1/86400)*count});
	       }else {
	           clearInterval(resend);
	           $(btnObject).html("&nbsp;获取验证码&nbsp;").attr('disabled',false);
	       }
	       count--;
	   }, 1000);
	 $(btnObject).attr('disabled',true);
}

</script>

</body>
</html>

效果如下:
验证码重新获取按钮