localStorage封装
/*设置与获取Cookie*/ 2 var Cookie ={} 3 Cookie.write = function(key, value, duration){ 4 var d = new Date(); 5 d.setTime(d.getTime()+1000*60*60*24*30); 6 document.cookie = key + "=" + encodeURI(value) + "; expires=" + d.toGMTString(); 7 }; 8 Cookie.read = function(key){ 9 var arr = document.cookie.match(new RegExp("(^| )"+key+"=([^;]*)(;|$)")); 10 if(arr != null) 11 return decodeURIComponent(arr[2]); 12 return ""; 13 }; 14 //定义本地存储对象 15 var storage = { 16 getItem:function(key){//假如浏览器支持本地存储则从localStorage里getItem,否则乖乖用Cookie 17 return window.localStorage? localStorage.getItem(key): Cookie.read(key); 18 }, 19 setItem:function(key,val){//假如浏览器支持本地存储则调用localStorage,否则乖乖用Cookie 20 if (window.localStorage) { 21 localStorage.setItem(key,val); 22 } else { 23 Cookie.write(key,val); 24 } 25 } 26 };
实例化:
storage.setItem("UserName","张三");//将UserName存进去 if(storage.getItem("UserName"))//假如存进去了 { console.log(storage.getItem("UserName"));//打印出来样子 }
因为localStorage存储进去的都是string类型,所以如果要存json记得存前读后做些处理
var myJson={"UserName","张三"}; storage.setItem("MyJson",JSON.stringify(myJson));//将myJson存进去,记得JSON.stringify转成字符串
var getmyJson=JSON.parse(storage.getItem("MyJson"));//取出来的是字符串,记得JSON.parse还原一下