方案一
1 <div class="div user-input"> 2 <input type="number" class="code" name="verify" placeholder="请输入手机验证码" required maxlength="6"> 3 <input type="button" class="obtain generate_code" value=" 获取验证码"> 4 </div> 5 <script type="text/javascript"> 6 $(function(){ 7 $(".generate_code").click(function(){ 8 var disabled = $(".generate_code").attr("disabled"); 9 if(disabled){ 10 return false; 11 } 12 if($("#mobile").val() == "" || isNaN($("#mobile").val()) || $("#mobile").val().length != 11 ){ 13 alert("请填写正确的手机号!"); 14 return false; 15 } 16 $.ajax({ 17 async:false, 18 type: "GET", 19 url: "{:U(‘User/sms‘)}", 20 data: {mobile:$("#mobile").val()}, 21 dataType: "json", 22 async:false, 23 success:function(data){ 24 console.log(data); 25 settime(); 26 }, 27 error:function(err){ 28 console.log(err); 29 } 30 }); 31 }); 32 var countdown=60; 33 var _generate_code = $(".generate_code"); 34 function settime() { 35 if (countdown == 0) { 36 _generate_code.attr("disabled",false); 37 _generate_code.val("获取验证码"); 38 countdown = 60; 39 return false; 40 } else { 41 $(".generate_code").attr("disabled", true); 42 _generate_code.val("重新发送(" + countdown + ")"); 43 countdown--; 44 } 45 setTimeout(function() { 46 settime(); 47 },1000); 48 } 49 }) 50 51 </script>
方案二
<div class="div user-input"> <input type="number" class="code" placeholder="请输入手机验证码" required maxlength="6"> <input type="button" class="obtain generate_code" value=" 获取验证码" onclick="settime(this);"> </div> <script type="text/javascript"> //倒计时 var countdown=60; function settime(val) { if (countdown == 0) { val.removeAttribute("disabled"); val.value="获取验证码"; countdown = 60; return false; } else { val.setAttribute("disabled", true); val.value="重新发送(" + countdown + ")"; countdown--; } setTimeout(function() { settime(val); },1000); } </script>
<原文地址http://blog.csdn.net/hj7jay/article/details/51433828