首頁  >  文章  >  web前端  >  JS基於遞歸實現倒數計時效果的方法

JS基於遞歸實現倒數計時效果的方法

高洛峰
高洛峰原創
2016-12-05 11:12:121739瀏覽

本文實例講述了JS基於遞歸實現倒數計時效果的方法。分享給大家參考,具體如下:

事件:

//发送验证码
$('.js-sms-code').click(function(){
    $(this).attr("disabled", "disabled").html("<span style=&#39;color:#666&#39;><span id=&#39;countdown&#39;>60</span>s 后再试</span>");
    countdown();
    var tel = $(&#39;#tel&#39;).val();
    $.ajax({
      url: "{sh::U(&#39;Home/sendSmscode&#39;)}",
      type:&#39;POST&#39;,
      dataType:"json",
      data: {tel: tel},
      success: function() {
      },
      error: function() {
        $(&#39;.js-help-info&#39;).html("请求失败");
      }
    });
})

點評:這裡的countdown方法就是妙處。

看代碼:

function countdown() { // 递归
  setTimeout(function() {
    var time = $("#countdown").text();
    if (time == 1) {
      $(&#39;.js-sms-code&#39;).removeAttr("disabled");
      $(&#39;.js-sms-code&#39;).html("发送验证码");
    } else {
      $("#countdown").text(time - 1);
      countdown();
    }
  }, 1000);
}

   

點評:如果time不等於1,就繼續調用,同時時間減去一秒鐘。 setTimeout也很精髓。直至time減到1為止,移除disabled並更改內容為『發送驗證碼'。


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn