美文网首页
前端本地存储localStorage,cookie

前端本地存储localStorage,cookie

作者: overflow_hidden | 来源:发表于2017-04-01 15:31 被阅读186次

    由于IE8一下浏览器不支持h5的localStorage。所以,在此将其与cookie的存储封装在一起。IE8很大部分也不支持localStorage,与安装的方式有关系。

    1.存储
    setStorage: function(obj) {
      var storage = window.localStorage;
      if (storage) {
        localStorage.setItem(obj.name, obj.value)
      } else {
        var _obj = obj.name + "=" + obj.value;
        document.cookie = _obj;
      }
    },
    
    2.获取
    getStorage: function(key) {
      var result = {};
      var storage = window.localStorage;
      if (storage) {
        return storage.getItem(key);
      } else {
        var cookie = document.cookie.split('; ');
        cookie.forEach(function(item) {
          var pair = item.split('=');
          result[pair[0]] = pair[1];
        });
        return result[key];
      }
    
    },
    
    3.删除
    deleteStorage: function(key) {
      var exp = new Date();
      var storage = window.localStorage;
      exp.setTime(exp.getTime() - 1);
      var value = this.getStorage(key);
      if (value != null) {
        storage ?
          storage.removeItem(key) :
          document.cookie = key + "=" + value + ";expires=" + exp.toGMTString();
      }
    },
    
    4.全部清除
     storageClear: function() {
      var exp = new Date();
      exp.setTime(exp.getTime() - 1);
      var cookie = document.cookie.split('; ');
      if (window.localStorage) {
        localStorage.clear();
      } else {
        if (cookie.length == 0) {
          return false;
        }
        cookie.forEach(function(item) {
          var pair = item.split('=');
          document.cookie = pair[0] + "=" + pair[1] + ";expires=" + exp.toGMTString();
        });
      }
    },

    相关文章

      网友评论

          本文标题:前端本地存储localStorage,cookie

          本文链接:https://www.haomeiwen.com/subject/elbiottx.html