Back

js - 发送短信倒计时30秒

发布时间: 2018-04-22 10:15:00

倒计时参考:   https://stackoverflow.com/questions/40638402/javascript-countdown-timer-with-start-stop-buttons

link disable/enable: https://stackoverflow.com/questions/3788946/how-do-i-dynamically-enable-disable-links-with-jquery

想实现个 倒计时的页面, 需要:

var myTimer;
function clock() {
   myTimer = setInterval(myClock, 1000);
   var c = 30;   // 倒计时30 秒

   function myClock() {

     $('#send_validation_code').text('请等待'+ (--c) + '秒')
     if (c == 0) {
       clearInterval(myTimer);
       $('#send_validation_code').text("发送验证码")
       $('#send_validation_code').unbind('click')   // 让按钮恢复点击
     }
   }
}

function send_validation_code(){
  mobile = $('#mobile').val()
  url = "/settings/send_validation_code?mobile=" + mobile

  jQuery.get(url, function(data){
    if(data.code == 0){
      alert('验证码已经发送到手机: ' + mobile)
      $('#send_validation_code').bind('click', function(e){  // 让按钮无法点击
        e.preventDefault();
      })
      clock()
    }else{
      alert(data.msg)
    }
  })
}

erb中的按钮:

<a class="btn btn-default btn-small" id="send_validation_code" style="width: 96px; text-align: center" href="javascript:send_validation_code()">发送验证码</a>

Back