js短信验证码倒计时(页面刷新无效)

实现思路通过添加cookie来实现刷新无效

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-1.11.2.min.js"></script>
    <script src="js/js.js"></script>

</head>
<body>
<div>
    <input type="button" id="obtain-code" value="获取验证码" class="obtain-code">
</div>
<script>
    $(function () {
        var countdown = 60;
        var cookie = getCookie("countdown");
        if (cookie != undefined) {
            jx.identifyingCode(countdown - parseInt((new Date().getTime() - cookie) / 1000));
        }
        $("#obtain-code").click(function () {
            addCookie("countdown", new Date().getTime(), countdown);
            jx.identifyingCode(countdown);
        })
    })
</script>
</body>
</html>
/**
 * Created by Administrator on 2017/7/25.
 */
var jx = {
    identifyingCode: function () {
        var e = {
            wait: arguments[0] ? arguments[0] : 60,
            showText: arguments[1] ? arguments[1] : "再次获取验证码",
            dynamicText: arguments[2] ? arguments[2] : "秒后再次获取",
            nextDynamicText: arguments[3] ? arguments[3] : "",
            hsTime: function (e) {
                if (t = $(this), 0 == this.wait) $(e).removeAttr("disabled").val(this.showText).removeClass("disabled").addClass("enable"), t.wait = this.wait; else {
                    var t = this;

                    $(e).prop("disabled", !0).val(this.nextDynamicText + t.wait + " " + this.dynamicText).removeClass("enable").addClass("disabled"), this.wait--, setTimeout(function () {
                        t.hsTime(e)
                    }, 1e3)
                }
            }
        };
        e.hsTime(".obtain-code")
    }
};
function addCookie(name, value, expiresHours) {
    var cookieString = name + "=" + escape(value);
    //判断是否设置过期时间,0代表关闭浏览器时失效
    if (expiresHours > 0) {
        var date = new Date();
        date.setTime(date.getTime() + expiresHours * 1000);
        cookieString = cookieString + ";expires=" + date.toUTCString();
    }
    document.cookie = cookieString;
}

//根据名字获取cookie的值
function getCookie(name) {
    var strCookie = document.cookie;
    var arrCookie = strCookie.split("; ");
    for (var i = 0; i < arrCookie.length; i++) {
        var arr = arrCookie[i].split("=");
        if (arr[0] == name) {
            return unescape(arr[1]);
            break;
        }
    }

}
//删除cookies
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookieValue(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

 完成代码下载

http://download.csdn.net/detail/u012192657/9910391

posted @ 2017-07-25 18:48  sunniejs  阅读(546)  评论(0编辑  收藏  举报