封装localStorage和cookie的方法

(function (win,doc) {
var GD16 = {
/**
* 创建localStorage
* @param argument json || string
*/
Items: function (argument) {
if (typeof argument == 'object') {//创建
for (var i in argument) {
win.localStorage.setItem(i, argument[i]);
}
}
else if (typeof argument == 'string') {//获取
return win.localStorage.getItem(argument);
}
else {
return console.error('参数只能是json|string');
}
},
/**
* 删除localStorage
* @param val string || null
*/
rmItem: function (val) {
if (val) {
win.localStorage.removeItem(val);
} else {
var json = window.localStorage;
for (var i in json) {
win.localStorage.removeItem(i);
}
}
},
/**
* 设置cookie|删除cookie|修改cookie
*/
setCookie: function (name, value, time) {
var d = new Date(new Date().getTime() + time * 1000).toGMTString();
document.cookie = '' + name + '=' + value + ';expires=' + d;
},
/**
* 获取cookie
* @param name
* @returns {string}
*/
getCookie: function (name) {
var arr = document.cookie.split('; ');
var value = '';
for (var i = 0, len = arr.length; i < len; i++) {
if (arr[i].split('=')[0] == name) {
value = arr[i].split('=')[1];
break;
}
}
return value;
}
};
win.GD16 = GD16;
})(window,document);

原文地址:https://www.cnblogs.com/li-123/p/6933223.html