看着水了一天的群,终于看到一段高质量的代码了分享一下localStorage

_history : { //缓存
			isLocalStorage:window.localStorage?true:false,
			set : function(key,value){ //设置缓存
				if(this.isLocalStorage){
					window.localStorage.setItem(key,value);
				}else{
					var expireDays = 365; //失效时间
					var exDate=new Date();
					exDate.setTime(exDate.getTime()+expireDays*24*60*60*1000);
					document.cookie=key + "=" + escape(value)+";expires=" + exDate.toGMTString();
				}
			},
			read : function(key){ //读取缓存
				if(this.isLocalStorage){
					return window.localStorage.getItem(key);
				}else{
					var arr,reg=new RegExp("(^| )"+key+"=([^;]*)(;|$)");
					if(arr=document.cookie.match(reg)){
						return unescape(arr[2]);
					}else{
						return null;
					}
				}
			},
			del : function(key){ //删除缓存
				if(this.isLocalStorage){
					localStorage.removeItem(key);
				}else{
					var exDate = new Date();
					exDate.setTime(exDate.getTime() - 1);
					var read_val=this.read(key);
					if(read_val!=null) document.cookie= key + "="+read_val+";expires="+exDate.toGMTString();
				}
			}
		},

 

缓存下用户操作 如果用户点击过”往返“我就缓存它 刷新或者下次打开就是往返

localStorage+cookie

 

posted @ 2015-04-09 15:22  一点点白  阅读(3001)  评论(0编辑  收藏  举报