12/07 发表评论

在《JavaScript高级程序设计》一书中发现一段代码,很值得借鉴:

var CookieUtil = {
    get: function(name) {
        var cookie = document.cookie;
        var cookieName = encodeURIComponent(name) + "=";
        var start = cookie.indexOf(cookieName);
        var value = null;
        if (start > -1)
        {
            var end = cookie.indexOf(";", start);
            if (end == -1)
                end = cookie.length;
            value = decodeURIComponent(cookie.substring(start + cookieName.length, end));
        }
        return value;
    },
    set: function(name, value, expires, path, domain, secure) {
        var 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;
    },
    unset: function(name, path, domain, secure) {
        this.set(name, "", new Date(0), path, domain, secure);
    }
};

// test
CookieUtil.set("name","tony");
alert(CookieUtil.get("name"));
CookieUtil.unset("name");
alert(CookieUtil.get("name"));

发表评论

回到顶端