js 本地存储

功能描述

默认使用 localStorage,降级使用 cookie,支持写入、读取、删除操作。

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// 本地存储
var localData = {
setLocal: function(name, value){
var name = encodeURIComponent(name),
value = encodeURIComponent(value);
if (typeof Storage != 'undefined') {
localStorage[name] = value;
} else {
var nowDate = new Date().getTime(),
expiresDate = nowDate + 1000*60*60*24*7,
expiresDateTime = Date(expiresDate);
document.cookie = name +'='+ value +'; expires='+ expiresDateTime +'; path=/';
}
},
getLocal: function(name){
var name = encodeURIComponent(name);
if (typeof Storage != 'undefined') {
return localStorage[name];
} else {
var name = name + '=';
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) return decodeURIComponent(c.substring(name.length,c.length));
}
return '';
}
},
delLocal: function(name){
var name = encodeURIComponent(name);
if (typeof Storage != 'undefined') {
localStorage.removeItem(name);
} else {
document.cookie = name +'='; expires='+ new Date(0) +'; path=/';
}
}
}

使用

1
2
3
4
5
6
// 写入
localData.setLocal('user', 'shuizhongxiong');
// 读取
var code = localData.getLocal('user');
// 删除
localData.delLocal('user');
------------- 本文结束 感谢您的阅读 -------------

本文标题:js 本地存储

文章作者:水中熊

发布时间:2018年06月11日 - 13:06

最后更新:2018年06月11日 - 15:06

原始链接:https://shuizhongxiong.github.io/js-localStorage.html

许可协议: 知识共享署名-非商业性使用-相同方式共享 3.0 中国大陆许可协议进行许可。 转载请保留原文链接及作者。

🌹坚持原创技术分享,您的支持将鼓励我继续创作!🌹
0%