返回顶部

收藏

HTML5本地存储localStorage使用示例

更多

支持JSON, Object, Date, String, Bool, Array序列化存储(localStorage),取值时自动反序列化

[JavaScript]代码

/**
* @name Util.storage, @cat Util/Storage, @function storage本地存储管理
* @example storage('the_storage'); Get the value of a storage.
* @example storage('the_storage', 'the_value'); Create a storage.
* @example storage('the_storage', null); delete one storage value
* @example storage(null); clean all storage
*/
Util.storage = $$.S = function(key, value){
    if(!Util.supportStorage()){
        Util.config('Storage_'+key, value);return;
    }
    if(arguments.length > 1 && 'string'===typeof key){
        if(null===value){
            localStorage.removeItem($$.app+'_'+key);
        }else{
            localStorage.setItem($$.app+'_'+key,Util.Serialize(value));
        }
    }else if('string'===typeof key){
        var value = Util.UnSerialize(localStorage.getItem($$.app+'_'+key));
        return value;
    }else if(null===key){
        localStorage.clear();
    }
    return this;//链式操作支持
}
Util.supportStorage = function(){
    return 'undefined' !==typeof window.localStorage;
}

[JavaScript]代码

Util.Serialize = function(obj){
    switch(obj.constructor){
        case Object:
            var str = '{';
            for(var o in obj) str += o + ':' + Util.Serialize(obj[o]) + ',';
            if(str.substr(str.length-1) == ',') str = str.substr(0,str.length -1);
            return str + '}';
            break;
        case Array:
            var str = '[';
            for(var o in obj) str += Util.Serialize(obj[o])+',';
            if(str.substr(str.length-1) == ',') str = str.substr(0,str.length -1);
            return str + ']';
            break;
        case String:  return '"'+obj.toString()+'"';  break;
        case Number:  return obj.toString();          break;
        case Boolean: return obj.toString();          break;
        case Date:    return '"'+obj.toString()+'"';  break;
        case Function:  break;
    }
};
Util.UnSerialize = function(obj){
    try{
        return eval('(' + obj + ')');
    }catch(e){
        throw new SyntaxError('Badly formed JSON string');
    }
};

标签:javascript,localStorage,html5

收藏

0人收藏

支持

0

反对

0

发表评论