您的位置:首页 > Web前端 > JavaScript

【javascript】js本地保存数据的一个解决方案:localStorage

2015-02-28 19:00 531 查看
'localStorage' : localData = {
   hname : location.hostname ? location.hostname+'/marchsoft/index.php/OA/' : '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 = exDate.getDate()+30;
            this.dataDom.expires = exDate.toUTCString();//设定过期时间
         }catch(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{
         if(this.initDom()){
            this.dataDom.load(this.hname);
            return this.dataDom.getAttribute(key);
         }
      }
   },
   add:function(key,value){
           var before = this.get(key);
           if(before != null){
               var add = true;
               var i = 0;
               for(i;i<before.length;++i){
                   if(value == this.get(key)[i]){
                       add = false;
                   }
               }
               if(add){
                   this.set(key,new Array(this.get(key),value));
               }
           }else{
               this.set(key,new Array(value));
           }
   },
   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);
         }
      }
   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: