封装localStorage
1 (function(){ 2 window.localData = { 3 hname:location.hostname?location.hostname:'localStatus', 4 isLocalStorage:window.localStorage?true:false, 5 dataDom:null, 6 7 initDom:function(){ 8 if(!this.dataDom){ 9 try{ 10 this.dataDom = document.createElement('input'); 11 this.dataDom.type = 'hidden'; 12 this.dataDom.style.display = "none"; 13 this.dataDom.addBehavior('#default#userData'); 14 document.body.appendChild(this.dataDom); 15 var exDate = new Date(); 16 exDate = exDate.getDate()+30; 17 this.dataDom.expires = exDate.toUTCString(); 18 }catch(ex){ 19 return false; 20 } 21 } 22 return true; 23 }, 24 set:function(key,value){ 25 if(this.isLocalStorage){ 26 window.localStorage.setItem(key,value); 27 }else{ 28 if(this.initDom()){ 29 this.dataDom.load(this.hname); 30 this.dataDom.setAttribute(key,value); 31 this.dataDom.save(this.hname) 32 } 33 } 34 }, 35 get:function(key){ 36 if(this.isLocalStorage){ 37 return window.localStorage.getItem(key); 38 }else{ 39 if(this.initDom()){ 40 this.dataDom.load(this.hname); 41 return this.dataDom.getAttribute(key); 42 } 43 } 44 }, 45 remove:function(key){ 46 if(this.isLocalStorage){ 47 localStorage.removeItem(key); 48 }else{ 49 if(this.initDom()){ 50 this.dataDom.load(this.hname); 51 this.dataDom.removeAttribute(key); 52 this.dataDom.save(this.hname) 53 } 54 } 55 } 56 } 57 58 var text = document.getElementById('localDataHook'); 59 var btn = document.getElementById('clearBtnHook'); 60 window.onbeforeunload = function(){ 61 localData.set('beiyuuData',text.value); 62 } 63 btn.onclick = function(){localData.remove('beiyuuData');text.value=''}; 64 if(localData.get('beiyuuData')){ 65 text.value = localData.get('beiyuuData'); 66 } 67 })()