新写了一个兼容ie,ff的Storage类,主要实现:
1.存储,
2.获取,
3.删除,
数据支持字符串/json
以下是源码:
Storage = (function(){
var isInit = false;
var obj = null;
var defDay = 365;
var isIE = ("\v" == "v");
var ikey = "Tenpay_Default_Data";
var domain = document.domain; //或者提取自己框架的
var initObj = function(){
if(isIE){
obj = document.createElement("div");
obj.id = "Default_JData_id";
obj.style.behavior = "url('#default#userData')"
document.body.appendChild(obj);
isInit = true;
}
};
var setExpire = function(day){
defDay = day;
};
var jsonToStr = function(json){
var list = [];
if("string" === typeof(json)) return "\""+ json.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
if("number" === typeof(json)) return json;
if("undefined" === typeof(json)) return "undefined";
if("object" === typeof(json)){
if(null === json){return null}
else if("function" === typeof(json.sort)){
for(var i = 0,len = json.length; i < len; i++){
list.push(jsonToStr(json[i]));
}
return "["+ list.join() +"]";
}else{
for(var i in json){
list.push(i + ":" + jsonToStr(json[i]));
}
return "{"+ list.join() +"}";
}
}
};
var strToJson = function(str){
return eval('('+ str +')');
};
var setData = function(name, value, domain_name, key, day){
ikey = key || ikey;
domain = domain_name || domain;
if(!isInit){initObj()};
if(value instanceof Object){
value = jsonToStr(value);
}
var d = new Date(),exps = (null != day ? day : defDay);
d.setSeconds(d.getSeconds() + exps * 24 * 3600);
try{if(isIE){
obj.load(ikey);
obj.setAttribute(name, value);
obj.expires = d.toUTCString();
obj.save(ikey);
}else if(window.globalStorage){
globalStorage[domain][ikey + "__" + name] = value;
globalStorage[domain][ikey + "__expire"] = d.getTime();
}}catch(e){}
};
var getData = function(name, domain_name, key){
ikey = key || ikey;
domain = domain_name || domain;
if(!isInit){initObj()};
try{
if(isIE){
obj.load(ikey);
return /^\{.*\}$|^\[.*\]$/.test(obj.getAttribute(name)) ? strToJson(obj.getAttribute(name)) : obj.getAttribute(name);
}else if(window.globalStorage){
var now = parseFloat((new Date()).getTime()), exp = parseFloat(globalStorage[domain][ikey + "__expire"]);
if (exp > now) {
return /^\{.*\}$|^\[.*\]$/.test(globalStorage[domain][ikey + "__" + name]) ? strToJson(globalStorage[domain][ikey + "__" + name]) : globalStorage[domain][ikey + "__" + name];
}else {
delData(name, key);
}
}
}catch(e) {
//exception
}
return "";
};
var delData = function(name, domain_name, key){
ikey = key || ikey;
domain = domain_name || domain;
if(!isInit){initObj()};
try {
if(isIE){
obj.load(ikey);
obj.removeAttribute(name);
obj.save(ikey);
}else if(window.globalStorage){
globalStorage[domain][ikey + "__" + name] = undefined;
globalStorage[domain].removeItem(ikey + "__" + name);
}
}catch (e) {}
};
return {
setExp : setExpire,
set : setData,
get : getData,
del : delData
};
})();
posted on 2010-01-06 22:28
jacklau 阅读(241)
评论(0) 编辑 收藏