浏览器本地存储(webStorage)

LoaclStorage

一种存在浏览器的域对象;并且关闭浏览器之后依然有效,只有手动清除或者清空缓存才会消失。

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>localStorage</title>
</head>
<body>
<h2>localStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="delData()">点我删除一个数据</button>
<button onclick="clearData()">点我清空数据</button>
<script type="text/javascript">
function saveData(){
//键值对形式,并且所有数据必须都是字符串
window.localStorage.setItem('msg','hello!')
let p = {name:'张三',age:18}
window.localStorage.setItem('person',JSON.stringify(p))
}

function readData(){
console.log(localStorage.getItem('msg'));
console.log(JSON.parse(localStorage.getItem('person')));
//当读取不存的数据时返回null并且JSON解析之后也是null
console.log(localStorage.getItem('msg3'));
}

function delData(){
localStorage.removeItem('msg');
}

function clearData(){
localStorage.clear();
}
</script>
</body>
</html>

SessionStorage

与localStorage功能类似的数据域对象,但是作用域会小于localStorage,关闭浏览器后清空。

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sessionStorage</title>
</head>
<body>
<h2>sessionStorage</h2>
<button onclick="saveData()">点我保存一个数据</button>
<button onclick="readData()">点我读取一个数据</button>
<button onclick="delData()">点我删除一个数据</button>
<button onclick="clearData()">点我清空数据</button>
<script type="text/javascript">
function saveData(){
//键值对形式,并且所有数据必须都是字符串
window.sessionStorage.setItem('msg','hello!')
let p = {name:'张三',age:18}
window.sessionStorage.setItem('person',JSON.stringify(p))
}

function readData(){
console.log(sessionStorage.getItem('msg'));
console.log(JSON.parse(sessionStorage.getItem('person')));
//当读取不存的数据时返回null并且JSON解析之后也是null
console.log(sessionStorage.getItem('msg3'));
}

function delData(){
sessionStorage.removeItem('msg');
}

function clearData(){
sessionStorage.clear();
}
</script>
</body>
</html>