JavaScript獲取驗證碼,60秒倒計時方法
阿新 • • 發佈:2018-11-03
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) } } }) });