JavaScript获取验证码,60秒倒计时方法

html

<div class="item-input code-box">
       <input type="text" class="username form-control" id="phone" placeholder="手机号" name="phone" />
       <button type="button" id="get_code">发送验证码</button>
</div>

js

        //获取验证码
        var wait = 60;

        function time(o) {
            if (wait == 0) {
                o.removeAttribute("disabled");
                o.innerHTML = "获取验证码";
                wait = 60;
            } else {
                o.setAttribute("disabled", true);
                o.innerHTML = wait + "秒后重新获取";
                wait--;
                setTimeout(function () {
                    time(o)
                }, 1000)
            }
        }
        $("#get_code").on("click", function () {
            var phone = $("input[name=phone]").val();
            var _this = document.getElementById("get_code");
            if (!phone) {
                alert('请输入手机号码')
                return false;
            } else if (!(/^1[34578]\d{9}$/.test(phone))) {
                alert('请输入正确的手机号码')
                return false;
            }
            $.ajax({
                type: "GET",
                url: "url",//请求验证码服务端地址
                success: function (data) {
                    if (data.success) {
                        time(_this); //倒计时
                    } else {
                        alert(data.msg)
                    }
                }
            })
        });

猜你喜欢

转载自blog.csdn.net/qq_29483485/article/details/83586121