Storage 的使用
从业多年,一直没啥心得记录,久之,觉悟有点遗憾,故随意发点…….
//是否不支持storage
isNoStorage: function(){ if(typeof(Storage)=="function" || window.sessionStorage){ return false; }else { return true; } },
// 保存 setStorage: function(key, value, isLocal){ var text = JSON.stringify({value: value}); if(isLocal) window.localStorage.setItem(key, text); //localStorage 方法存储的数据没有时间限制。第二天、第二周或下一年之后,数据依然可用。 else window.sessionStorage.setItem(key, text); // sessionStorage闭浏览器窗口后,数据会被删除。 },
// 提取 getStorage: function(key, isLocal){ var text; if (isLocal) text = window.localStorage.getItem(key); else text = window.sessionStorage.getItem(key); if (!text) return null; var obj = JSON.parse(text); if (obj) return obj.value; },
// 移除 removeStorage: function(key, isLocal){ if (isLocal) window.localStorage.removeItem(key); else window.sessionStorage.removeItem( key ); },
// 清除所有 clearStorage: function(){ window.localStorage.clear(); },
// 清理过期Storage (value值为日期 )
clearExpireStorage: function(curTime, key, isLocal){
var Storage = isLocal ? window.localStorage : window.sessionStorage;
var expireTime = 7*24*3600*1000;
for(var i=0, leng=Storage.length; i<leng; i++){
var skey = Storage.key(i);
var value = Storage.getItem(key);
if(key==skey.substring(0,key.length) && ((Number(curTime)-Number(value))>expireTime)){
Storage.removeItem(skey)
}
}
}