说明
以往只用js实现倒计时,如果刷新页面,倒计时就不能用了。现在用cookie满足刷新或重新打开页面后倒计时依然能用。
依赖库
jQuery
获取验证码按钮
<input id="second" type="button" value="免费获取验证码" />
js对cookie的操作
//发送验证码时添加cookie
function addCookie(name, value, expiresHours) {
var cookieString = name + "=" + escape(value);
//判断是否设置过期时间,0代表关闭浏览器时失效
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000);
cookieString = cookieString + ";expires=" + date.toUTCString();
}
document.cookie = cookieString;
}
//修改cookie的值
function editCookie(name, value, expiresHours) {
var cookieString = name + "=" + escape(value);
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000); //单位是毫秒
cookieString = cookieString + ";expires=" + date.toGMTString();
}
document.cookie = cookieString;
}
//根据名字获取cookie的值
function getCookieValue(name) {
var strCookie = document.cookie;
var arrCookie = strCookie.split("; ");
for (var i = 0; i < arrCookie.length; i++) {
var arr = arrCookie[i].split("=");
if (arr[0] == name) {
return unescape(arr[1]);
break;
}
}
}
主要逻辑代码
$(document).ready(function () {
// 绑定事件(点击按钮,发送验证码)
$("#second").click(function () {
send(this);
});
// 页面加载完成后,从cookie中获取剩余倒计时秒数。默认值为0
v = getCookieValue("secondsremained") ? getCookieValue("secondsremained") : 0;
// 如果cookie中倒计时时间不为0,则设置倒计时间
if (v > 0) {
settime(document.getElementById("second"), v);//开始倒计时
}
});
// 发送验证码、、
function send(_this) {
var mobile = $("#text").val();
var reg = /^1[3|4|5|7|8][0-9]{9}$/;
if (reg.test(mobile)) {
$.ajax({
type:"GET",
async : false,
cache : false,
url:"../user/sendCode",
data:{mobile:mobile},
dataType:"json",
success:function(result){
if (result.isSuccess){
// 把'剩余倒计时时间'保存到cookie中,有效时间60s
addCookie("secondsremained", 60, 60);
// 开始倒计时
settime(_this,60);
}else {
alert("发送失败");
}
}
});
} else {
$("#message").removeClass("hidden");
setTimeout('$("#message").addClass("hidden");', 3000);
}
}
// 设置倒计时时间
function settime(getCodeBtn, countdown) {
if (countdown == 0) {
getCodeBtn.removeAttribute("disabled");
getCodeBtn.value = "获取验证码";
return false;
} else {
getCodeBtn.setAttribute("disabled", true);
getCodeBtn.value = "重新发送(" + countdown + "s)";
countdown--;
editCookie("secondsremained", countdown, countdown);
}
setTimeout(function () {
settime(getCodeBtn, countdown);
}, 1000)
}
参考