发送手机验证码后的倒计时与锁定

发送短信验证码的按钮为

1
<a onclick="sendMsg()" id="sendMsg" class="get_code fr">获取手机验证码</a>

则先定义一个锁变量

1
var issendMsg = 1;

发送短信验证码的函数为调用 ajax 发送

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
var mobiletest =
/^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
function sendMsg() {
var mobile = $('input[name="mobile"]').val();
if (!mobiletest.test(mobile)) {
layer.msg("电话号码输入错误", { icon: 5 });
} else {
if (issendMsg) {
issendMsg = 0;
$.ajax({
type: "post",
url: "{:U('Ajax/sendmsg')}",
dataType: "json",
data: { mobile: mobile },
success: function (data) {
if (data["status"] > 0) {
layer.msg(data["info"]);
timecount();
} else {
layer.msg(data["info"], { icon: 5 });
}
},
});
}
}
}
</script>

定时函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>
var start = 60;
function timecount(start) {
if (start == 0) {
$("#sendMsg").html("获取手机验证码");
issendMsg = 1;
start = 60;
} else {
$("#sendMsg").html("已发送" + start + "秒");
start--;
}
setTimeout(function () {
timecount(start);
}, 1000);
}
</script>