舉報(bào) jquery 封裝 localStorage, sessionStorage, cookie. localStorage 支持過期設(shè)置

var script=document.createElement("script");  
script.setAttribute("type", "text/javascript");  
script.setAttribute("src", "http://code.jquery.com/jquery-1.8.3.min.js");  
var heads = document.getElementsByTagName("head");  
if(heads.length) heads[0].appendChild(script);  
else document.documentElement.appendChild(script); 
script.onload = function(){
(function(){
    $.extend({
                isJson : function(str) {
                    if ($.type(str)== 'string') {
                        try {
                            var obj=JSON.parse(str);
                            if($.type(obj) == 'object' && obj ){
                                return true;
                            } else {
                                return false;
                            }
                        } catch(e) {
                            //console.log('error:'+str+'!!!'+e);
                            return false;
                        }
                    }
                    return false;
                },
                storage : function(name, value, expire){
                    // expire 參數(shù) 格式 {expire : 1} 注:expire.expire 的值 等于過期時(shí)間減去當(dāng)前時(shí)間, 一個(gè)大于0的值,單位毫秒。
                    //判斷全局是否過期
                    var expires = JSON.parse(localStorage.getItem('expire')) || {'expire': 0};
                    if(expires.expire && expires.expire < new Date().getTime()) this.removeStorage();
                    //沒有參數(shù)時(shí),返回原生 localStorage
                    if(arguments.length == 0) return localStorage;
                    if(arguments[0] == null || arguments[0] == "") return;
                    if(name && name in expires && expires[name] && expires[name] < new Date().getTime()){
                        this.removeStorage(name);
                        delete expires[name];
                        localStorage.setItem('expire', JSON.stringify(expires));
                    }
                    if(arguments.length == 1){
                        if($.type(arguments[0]) == 'string'){
                            //只有一個(gè)字符串參數(shù) 'expire' 時(shí) 返回全局的過期時(shí)間
                            if(arguments[0] == 'expire' || arguments[0] == ':') return expires.expire;
                            //只有一個(gè)字符串參數(shù) 'expires' 時(shí) 返回json數(shù)據(jù) 所有的過期時(shí)間  包含全局
                            if(arguments[0] == 'expires' || arguments[0] == '::') return expires;
                            //只有一個(gè)字符串參數(shù) 以冒號(hào)或雙冒號(hào)開頭的字符串 冒號(hào)后面是要查找到 [name] 返回[name]的過期時(shí)間
                            if(/^:{1,2}[\w-]+$/.test(arguments[0])){
                                name = arguments[0].replace(/^:{1,2}([\w-]+)$/);
                                if(name in expires && expires.name) return expires[name];
                                return 0;
                            }
                            //只有一個(gè)字符串參數(shù)時(shí),返回當(dāng)前的值
                            var ret = localStorage.getItem(name)
                            if(this.isJson(ret)) ret = JSON.parse(ret);
                            return ret;
                        }
                        //只有一個(gè) json對(duì)象參數(shù)并且它包含expire屬性
                        if($.type(arguments[0]) == 'object' && 'expire' in arguments[0] && arguments[0].expire){
                            //值為字符串時(shí) 字符串是要查找到 [name] 返回[name]的過期時(shí)間
                            if($.type(arguments[0].expire) == 'string'){
                                name = arguments[0].expire;
                                if(name in expires && expires.name) return expires[name];
                                return 0;
                            }
                            //值為數(shù)字時(shí) 設(shè)置全局過期時(shí)間
                            if($.type(arguments[0].expire) == 'number'){
                                expires.expire = new Date().getTime() + arguments[0].expire;
                                localStorage.setItem('expire', JSON.stringify(expires));
                            }
                        }
                    }
                    //有2個(gè)參數(shù) 第1個(gè)是字符串,第2個(gè)是 expire對(duì)象時(shí)
                    if(arguments.length == 2 && $.type(arguments[0]) == 'string' && arguments[0] != '' && $.type(arguments[1]) == 'object' && Object.keys(arguments[1]).length == 1 && 'expire' in arguments[1]) expire = arguments[1].expire;  
                    //保存當(dāng)前 expire
                    if(expire && $.type(expire) == 'object'){
                        expires[name] = new Date().getTime() + expire.expire;
                        localStorage.setItem('expire', JSON.stringify(expires))
                    }
                    if(value == null || value == "") return this;
                    if($.type(value) == 'object' || $.type(value) == 'array') value = JSON.stringify(arguments[1]);
                    localStorage.setItem(name, value);
                    return this;
                },
                removeStorage : function(name){
                    if(name == null) localStorage.clear();
                    else localStorage.removeItem(name);
                    return this;
                },
                session : function(name, value){
                    if(name == null) return sessionStorage; //沒有參數(shù)時(shí),返回原生 sessionStorage
                    if(value == null){
                        var ret = sessionStorage.getItem(name);
                        if(this.isJson(ret)) ret = JSON.parse(ret);
                        return ret;
                    }
                    if($.type(value) == 'object' || $.type(value) == 'array') value = JSON.stringify(value);
                    sessionStorage.setItem(name, value);
                    return this;
                },
                removeSession : function(name){
                    if(name == null) sessionStorage.clear();
                    else sessionStorage.removeItem(name);
                    return this;
                },
                cookie : function(name, value, options){
                    var cookie = document.cookie.replace(' ', '');
                    //當(dāng)沒有參數(shù)時(shí) 返回原生 cookie 對(duì)象
                    if(arguments.length == 0) return unescape(cookie); 
                    if(name == null || $.type(name) != 'string' ||  name == '') return;
                    //當(dāng)只有一個(gè)參數(shù)時(shí) 返回 value 值, 當(dāng)?shù)诙?shù)為布爾型時(shí) true : 返回 json 所有數(shù)據(jù)。 false : 與一個(gè)參數(shù)時(shí)相同。
                    if(arguments.length == 1 || (arguments.length == 2 && $.type(arguments[1]) == 'boolean')){
                        var json = {};
                        $.each(cookie.split(';'), function(i,str){
                            var arr = str.split('=');
                            json[arr[0]] = unescape(arr[1]);
                        });
                        if(arguments.length == 2 && arguments[1]) return json;
                        //讀取 name 值
                        var ret = unescape(json[name]);
                        //如果是JSON字符串,轉(zhuǎn)成JSON對(duì)象
                        if(this.isJson(ret)) ret = JSON.parse(ret);
                        return ret;
                    }
                    //以下是寫入cookie
                    var str = ';';
                    // json { domain : '', path : '', expires : 0, secure : '' } expire 或  expires 都可以  單位豪秒
                    // expire 或  expires  參數(shù) 格式 {expire : 1}   注:expire.expire 的值 等于過期時(shí)間減去當(dāng)前時(shí)間, 一個(gè)大于0的值,單位毫秒。
                    if(options || $.type(options) == 'object'){
                        //把 expire 屬性 修正為 expires
                        if('expire' in options && options.expire && $.type(options.expire) == 'number'){
                            options.expires = options.expire;
                            delete options.expire;
                        }
                        //處理過期時(shí)間,單位毫秒
                        if('expires' in options && options.expires && $.type(options.expires) == 'number'){
                            var exp = new Date();
                            exp.setTime(exp.getTime() + options.expires); 
                            options.expires = exp.toGMTString();
                        }
                        for(var key in options){
                            str += key + '=' + options[key] + ';';
                        }
                    }
                    document.cookie = name + "=" + escape(value) + str;
                    return this;
                },
                removeCookie : function(name, options){
                    return this.cookie(name, '',  $.extend(options, {expires: -1}));
                }
            });
})(jQuery);

$.storage('a','localStorage');
console.log($.storage('a'))
$.removeStorage('a');
console.log($.storage('a'));

$.session('b','sessionStorage');
console.log($.session('b'))
$.removeSession('b');
console.log($.session('b'));

$.cookie('c','cookie');
console.log($.cookie('c'))
$.removeCookie('c');
console.log($.cookie('c'));
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容