JS获取验证码后倒计时不受刷新及关闭影响

时间:2021-09-17 10:49:14

HTML部分

<input type="button" id="code_btn" value="获取验证码">   

JS部分

//获取验证码
$(function() {
$("#code_btn").on("tap", function() {
if(!rex.test($("#tel").val())) {
tip("请输入正确手机号");
return false;
}
$.ajax({
async: false,
cache: false,
type: 'POST',
url: forgetConfirmUrl, // 请求的action路径
data: {
phone: $("#tel").val()
},
dataType: "json",
success: function(data) {
console.log(data);
if(data.error_code == 0) {
tip("发送成功");
} else if(data.error_code == 1) {
tip("用户未注册");
} else if(data.error_code == 2) {
tip("手机号值为空");
} else if(data.error_code == 3) {
tip("手机号格式不正确");
} else {
tip("网络异常");
}
}
});
addCookie("secondsremained", 60, 60); //添加cookie记录,有效时间60s
settime($("#code_btn")); //开始倒计时
})
var v = getCookieValue("secondsremained") ? getCookieValue("secondsremained") : 0;//获取cookie值 if(v > 0) {
settime($("#code_btn")); //开始倒计时
}
})
//发送验证码时添加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;
}
} } //开始倒计时
var countdown;
function settime(obj) {
countdown = getCookieValue("secondsremained");
var tim = setInterval(function() {
countdown--;
obj.attr("disabled", true);
obj.attr("value", "重新发送(" + countdown + ")");
if(countdown <= 0 ) {
clearInterval(tim);
$(obj).removeAttr("disabled");
$(obj).attr("value", "请输入验证码");
}
editCookie("secondsremained", countdown, countdown + 1);
}, 1000) //每1000毫秒执行一次 }