JS封装Cookie

var CookieUtil = {
        // 设置cookie
        set : function (name, value, expires, domain, path, secure) {
            var cookieText = "";
            cookieText += encodeURIComponent(name) + "=" + encodeURIComponent(value);
            if (expires instanceof Date) {
                cookieText += "; expires=" + expires.toGMTString();
            }
            if (path) {
                cookieText += "; path=" + path;
            }
            if (domain) {
                cookieText += "; domain=" + domain;
            }
            if (secure) {
                cookieText += "; secure";
            }
            document.cookie = cookieText;
        },
        // name=value; expires=expiration_time; path=domain_path; domain=domain_name; secure
        // 获取cookie
        get : function (name) {
            var cookieName = encodeURIComponent(name) + "=",
                cookieStart = document.cookie.indexOf(cookieName),
                cookieValue = "";
            if (cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf (";", cookieStart);
                if (cookieEnd == -1) {
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
            }
            return cookieValue; 
        },
        // 删除cookie
        unset : function (name, domain, path, secure) {
            this.set(name, "", Date(0), domain, path, secure);
        }
    };
    // 测试
    CookieUtil.set("name", "zhang");
    var name = CookieUtil.get("name");
    alert(name);    // zhang
    CookieUtil.unset("name");
    alert(CookieUtil.get("name"));  // 空

  参考:https://www.cnblogs.com/lxf1117/p/6435612.html

posted @ 2018-07-17 17:41  MeetU  阅读(211)  评论(0编辑  收藏  举报