本文实例讲述了JS基于递归实现倒计时效果的方法。分享给大家供大家参考,具体如下:
事件://发送验证码
$('.js-sms-code').click(function(){
$(this).attr("disabled", "disabled").html("60s 后再试");
countdown();
var tel = $('#tel').val();
$.ajax({
url: "{sh::U('Home/sendSmscode')}",
type:'POST',
dataType:"json",
data: {tel: tel},
success: function() {
},
error: function() {
$('.js-help-info').html("请求失败");
}
});
})
点评:这里的countdown方法就是妙处。
看代码:function countdown() { // 递归
setTimeout(function() {
var time = $("#countdown").text();
if (time == 1) {
$('.js-sms-code').removeAttr("disabled");
$('.js-sms-code').html("发送验证码");
} else {
$("#countdown").text(time - 1);
countdown();
}
}, 1000);
}
点评:如果time不等于1,就继续调用,同时时间减去一秒。setTimeout也很精髓。直至time减到1为止,移除disabled并更改内容为‘发送验证码'。
本文原创发布php中文网,转载请注明出处,感谢您的尊重!
专题推荐:JS