方法一:(setInterval)
$("#getCode").on("click", getCodeClick); function getCodeClick() { $("#getCode").off("click"); try { new common.ajaxRequest({ url: url+"cmbntUser/getChangePhoneAuthCode?mobilePhone="+ $("#txtMobile").val().trim(), type: "POST", param: '', dataType: "json", header: header, callBack: function (result) { if(result.type =="SUCCESS"){ var lefttime = 60; $("#getCode").attr("disabled", "disabled"); $("#getCode").html("60秒后重新获取"); var countDown = setInterval(function () { lefttime--; $("#getCode").html(lefttime + "秒后重新获取"); if (0 == lefttime) { $("#getCode").html("重新获取"); $("#getCode").removeAttr("disabled"); $("#getCode").on("click", getCodeClick); clearInterval(countDown); } }, 1000); }else{ $("#getCode").on("click", getCodeClick); } } }); } catch (ex) { $("#ErrMessage").html("发送短信失败,请稍后再试。"); $("#ErrMessage").attr("class", "tip textred"); } return false; }
方法二:(setTimeout)
function setTime(time){ time --; $('#msgCodeBtn').attr('disabled',true).html(time+'秒后重新获取'); var timeT = setTimeout(function(){ setTime(time)
},1000); if(time == 0){ $('#msgCodeBtn').removeAttr('disabled').html('重新获取'); clearTimeout(timeT); } } //发送验证码 $('#msgCodeBtn').on('click',function(){ var time = 60; $('#msgCodeBtn').html('60秒后重新获取'); setTime(time); });