时间:2021-07-01 10:21:17 帮助过:8人阅读
事件:
- //发送验证码
- $('.js-sms-code').click(function(){
- $(this).attr("disabled", "disabled").html("<span style='color:#666'><span id='countdown'>60</span>s 后再试</span>");
- countdown();
- var tel = $('#tel').val();
- $.ajax({
- url: "{sh::U('Home/sendSmscode')}",
- type:'POST',
- dataType:"json",
- data: {tel: tel},
- success: function() {
- },
- error: function() {
- $('.js-help-info').html("请求失败");
- }
- });
- })
点评:这里的countdown方法就是妙处。
看代码:
- function countdown() { // 递归
- setTimeout(function() {
- var time = $("#countdown").text();
- if (time == 1) {
- $('.js-sms-code').removeAttr("disabled");
- $('.js-sms-code').html("发送验证码");
- } else {
- $("#countdown").text(time - 1);
- countdown();
- }
- }, 1000);
- }
点评:如果time不等于1,就继续调用,同时时间减去一秒。setTimeout也很精髓。直至time减到1为止,移除disabled并更改内容为‘发送验证码'。