1
2
3
|
localStorage.setItem(
"user_name"
,
"hangge.com"
);
var
userName = localStorage.getItem(
"user_name"
);
|
1
2
3
|
localStorage.setItem(
"user_age"
,100);
var
userAge = Number(localStorage.getItem(
"user_age"
));
|
1
2
3
4
5
6
7
8
9
10
|
//创建日期对象
var
today =
new
Date();
//按照YYY/MM/DD的标准格式把日期转换成文本字符串,然后保存为文本
var
todayString = today.getFullYear() +
"/"
+ today.getMonth() +
"/"
+ today.getDate();
localStorage.setItem(
"session_started"
, todayString);
//取得日期文本,并基于该文本创建新的日期对象
var
newToday =
new
Date(localStorage.getItem(
"session_started"
));
alert(newToday.getFullYear());
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//自定义一个User对象
function
User(n, a, t) {
this
.name = n;
this
.age = a;
this
.telephone = t;
}
//创建User对象
var
user =
new
User(
"hangge"
, 100,
"123456"
);
//将其保存为方便的JSON格式
sessionStorage.setItem(
"user"
, JSON.stringify(user));
//跳转页面
//window.location = "hangge.html";
//将JSON文本转回原来的对象
var
user2 = JSON.parse(sessionStorage.getItem(
"user"
));
alert(user2.name);
|
1
2
3
|
if
(localStorage.getItem(
"user_name"
) ==
null
){
alert(
"用户名不存在!"
);
}
|
1
|
localStorage.removeItem(
"user_name"
);
|
1
|
localStorage.clear();
|
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
|
function
findAllItems() {
//取得用于保存数据项的
var
itemList = document.getElementById(
"itemList"
);
//清除列表
itemList.innerHTML =
""
;
//遍历所有数据项
for
(
var
i=0; i
//取得当前位置数据项的键
var
key = localStorage.key(i);
//取得以该键保存的数据值
var
item = localStorage.getItem(key);
//用以上数据创建一个列表项添加到页面中
var
newItem = document.createElement(
"li"
);
newItem.innerHTML = key +
": "
+ item;
itemList.appendChild(newItem);
}
}
|
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
38
39
40
41
42
43
44
45
46
|
fieldset {
margin-bottom: 15px;
padding: 10px;
}
label {
width: 40px;
display: inline-block;
margin: 6px;
}
input {
margin-top: 12px;
width: 200px;
}
function
addValue() {
// 取得两个文本框中的值
var
key = document.getElementById(
"key"
).value;
var
item = document.getElementById(
"item"
).value;
// 在本地存储中保存数据项
// (如果同名键已经存在,则用新值替换旧值)
localStorage.setItem(key, item);
}
|
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
|
#updateMessage {
font-weight: bold;
}
window.onload =
function
() {
alert(1);
//给window.onStorage事件添加一个处理函数
window.addEventListener(
"storage"
, storageChanged,
false
);
};
function
storageChanged(e) {
alert(2);
var
message = document.getElementById(
"updateMessage"
);
message.innerHTML =
"Local storage updated."
;
message.innerHTML +=
"
+ e.key;
message.innerHTML +=
"
+ e.oldValue;
message.innerHTML +=
"
+ e.newValue;
message.innerHTML +=
"
+ e.url;
}
|