Jquery点击发送按钮后,按钮文本倒计时

1.html代码

<input type="number" id="mobileNo" placeholder="请输入手机号" />
<input type="button" id="btnGetCode" style="background-color:#68BE02;color: #FFFFFF;border:0 solid #ccc;margin-bottom: 5%;width: 100%;height: 40px;" value="获取验证码"/>

<button id="btnDownload" style="color: #FFFFFF;border:0 solid #ccc;margin-top: 5%;width: 100%;height: 40px;">确认下载</button>

2.JS代码

function change_state(status) {
            var btnGetCode = $('#btnGetCode');
            var sending = "发送中...";
            var sent = "重新获取";
            var ticks = 60;
            var tick=function () {
                if (ticks > 0) {
                    setTimeout(function() {
                        btnGetCode.val(sent + "(" + ticks + ")");
                        ticks--;
                        tick();
                    }, 1000);
                } else {
                    change_state('retry');
                }
            };
            ticks = 60;
            switch (status) {
                case "sending":
                    {
                        $("#btnGetCode").attr("disabled",true);
                        btnGetCode.val(sending);
                        break;
                    }
                case "tick":
                    {
                        $("#btnGetCode").attr("disabled",true);
                        tick(sent);
                        break;
                    }
                case "retry":
                    {
                        $("#btnGetCode").attr("disabled",false);
                        btnGetCode.val(sent);
                        break;
                    }
            }
        };

3.方法调用

 $("#btnGetCode").click(function(){
        
        change_state('sending');
        var mobileNumber = $("#mobileNo").val();
        $.ajax({
            url: "/Share/SendVerfCode",
            type: "post",
            data: { mobileNo: mobileNumber },
            async: true,
            success: function (result) {
                alert(result.msg);
                if(result.state){
                    change_state("tick");
                }else{
                    change_state("retry");
                }
            },
            error: function () {
                alert("短信验证码发送失败");
            }
        });
    });

 

posted on 2016-04-20 11:07  CeleryCabbage  阅读(422)  评论(0编辑  收藏  举报

导航