h5新增了本地存儲localStorage,sessionStorage。UserData是微軟爲IE專門在系統中開闢的一塊存儲空間。
chrome, safari, firefox, ie 9都支持 localStorage.。IE6,7需要使用userData進行兼容。 使用 cookie不但容量有限,而且給我們增加了不少的帶寬,也進行影響網站的性能。
封裝代碼如下:
var localData = {
hname:location.hostname?location.hostname:'localStatus',
isLocalStorage:window.localStorage?true:false,
dataDom:null,
initDom:function(){ //初始化userData
if(!this.dataDom){
try{
this.dataDom = document.createElement('input');//這裏使用hidden的input元素
this.dataDom.type = 'hidden';
this.dataDom.style.display = "none";
this.dataDom.addBehavior('#default#userData');//這是userData的語法
document.body.appendChild(this.dataDom);
var exDate = new Date();
exDate.setDate(exDate.getDate()+30); //修改!!!
this.dataDom.expires = exDate.toUTCString();//設定過期時間
}catch(ex){
console.log(ex);
return false;
}
}
return true;
},
set:function(key,value){
if(this.isLocalStorage){
window.localStorage.setItem(key,value);
}else{
if(this.initDom()){
this.dataDom.load(this.hname);
this.dataDom.setAttribute(key,value);
this.dataDom.save(this.hname)
}
}
},
get:function(key){
if(this.isLocalStorage){
return window.localStorage.getItem(key);
}else{
console.log("get-userdata");
if(this.initDom()){
console.log(this.dataDom);
this.dataDom.load(this.hname);
return this.dataDom.getAttribute(key);
}
}
},
remove:function(key){
if(this.isLocalStorage){
localStorage.removeItem(key);
}else{
if(this.initDom()){
this.dataDom.load(this.hname);
this.dataDom.removeAttribute(key);
this.dataDom.save(this.hname)
}
}
}
}
//基本測試:主流瀏覽器及IE下測試通過
localData.set('lala','123');
console.log("00",localData.get("lala")); //123
console.log("11",localData.get("la")); //null
本文參考文章:js本地存儲解決方案(localStorage與userData)
原文中代碼設置expires處有錯誤,本文已經糾正。