当前位置:Gxlcms > JavaScript > JS基于递归实现倒计时效果的方法

JS基于递归实现倒计时效果的方法

时间:2021-07-01 10:21:17 帮助过:8人阅读

本文实例讲述了JS基于递归实现倒计时效果的方法。分享给大家供大家参考,具体如下:

事件:

  1. //发送验证码
  2. $('.js-sms-code').click(function(){
  3. $(this).attr("disabled", "disabled").html("<span style='color:#666'><span id='countdown'>60</span>s 后再试</span>");
  4. countdown();
  5. var tel = $('#tel').val();
  6. $.ajax({
  7. url: "{sh::U('Home/sendSmscode')}",
  8. type:'POST',
  9. dataType:"json",
  10. data: {tel: tel},
  11. success: function() {
  12. },
  13. error: function() {
  14. $('.js-help-info').html("请求失败");
  15. }
  16. });
  17. })

点评:这里的countdown方法就是妙处。

看代码:

  1. function countdown() { // 递归
  2. setTimeout(function() {
  3. var time = $("#countdown").text();
  4. if (time == 1) {
  5. $('.js-sms-code').removeAttr("disabled");
  6. $('.js-sms-code').html("发送验证码");
  7. } else {
  8. $("#countdown").text(time - 1);
  9. countdown();
  10. }
  11. }, 1000);
  12. }

点评:如果time不等于1,就继续调用,同时时间减去一秒。setTimeout也很精髓。直至time减到1为止,移除disabled并更改内容为‘发送验证码'。

人气教程排行