js cookie 操作 封裝


pCookie.js

(function(){

    var PotatogCookie = {};
    
    //設置cookie
    PotatogCookie.set = function(key, value, delay)
    {
        //默認cookie為七天之后過期 3s 4m 5h 7d 秒 分 時 天
        if(delay == "undefined")delay = "7d";
        delay = delay.toLowerCase();
        
        var expireDate = new Date();
        
        var num = parseInt(delay);
        if(delay.indexOf("d") !== -1)
        {
            expireDate.setDate(expireDate.getDate() + num);
        }
        else if(delay.indexOf("h") !== -1)
        {
            expireDate.setHours(expireDate.getHours() + num);
        }
        else if(delay.indexOf("m") !== -1)
        {
            expireDate.setMinutes(expireDate.getMinutes() + num);
        }
        else if(delay.indexOf("s") !== -1)
        {
            expireDate.setSeconds(expireDate.getSeconds() + num);
        }
        else
        {
            expireDate.setDate(expireDate.getDate() + num);
        }
        if(typeof value == "object")
        {
            value = JSON.stringify(value);
        }
        value = escape(value);
        document.cookie = key + "=" + value + ";expires=" + expireDate.toGMTString();
        return this.get(key);
    }
    
    //得到cookie 如果不存在 返回 undefined
    PotatogCookie.get = function(key)
    {
        var objCookie = {};
        var cookie = document.cookie;
        var keyValueList = cookie.split(";");
        for(var index in keyValueList)
        {
            var keyValue = keyValueList[index].split("=");
            var k = keyValue[0].trim();
            var v = keyValue[1];
         v = unescape(v); v
= this.decodeJson(v); objCookie[k] = v; } if(typeof key == "undefined") { return objCookie; } return objCookie[key]; } //刪除cookie PotatogCookie.del = function(key) { //刪除所有cookie if(typeof key == "undefined") { var cookieList = this.get(); for(key in cookieList) { this.del(key); } return true; } else { if(this.get(key) == "undefined") { return false; } else { return this.set(key,'',"0s"); } } } PotatogCookie.decodeJson = function(value) { //數組轉成的對象字符串 var regAryStr = /^\[[\s|\S]*\]$/; //對象轉成的對象字符串 var regObjStr = /^\{([\"\s|\S]+\"\:\"[\s|\S]*)+\"\}$/; if(regAryStr.test(value)) { return eval("(" + value + ")"); } if(regObjStr.test(value)) { return JSON.parse(value); } return value; } window.pCookie = PotatogCookie; })(window);

demo.html

使用方式

設置cookie

pCookie.set("name","張三","7d");

讀取cookie 如果不存在 返回undefined

var name = pCookie.get("name");不傳參表示獲得所有

刪除cookie

pCookie.del("name");不傳參表示刪除所有


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM