由于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();
});
}
},
网友评论