web储存
HTML5 web 存储,一个比cookie更好的本地存储方式。
# 什么是 HTML5 Web 存储?
使用HTML5可以在本地存储用户的浏览数据。
它也可以存储大量的数据,而不影响网站的性能.
数据以 键/值 对存在, web网页的数据只允许该网页访问使用。
# support or not
if(typeof(Storage)!=="undefined"){
alert('support it ')
}
else {
alert ('sorry it cannot support ')
}
1
2
3
4
5
6
2
3
4
5
6
# localStorage
用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去除。
there we show a demo
<p id="one"></p>
<button id="add" onclick="addnumber()">AddAge</button>
<script>
function addnumber(){
if(localStorage.age){
localStorage.age= Number(localStorage.age)+1 //you find when you close the browser the age is still the last value
document.getElementById('one').innerHTML=localStorage.age
}
else{
localStorage.age=33
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
localStorage.age=xxx
key="age",value="xxx"
# 移除 localStorage
localStorage.removeItem("age");
1
不管是 localStorage,还是 sessionStorage,可使用的API都相同,常用的有如下几个(以localStorage为例):
- 保存数据:localStorage.setItem(key,value);
- 读取数据:localStorage.getItem(key);
- 删除单个数据:localStorage.removeItem(key);
- 删除所有数据:localStorage.clear();
- 得到某个索引的key:localStorage.key(index);
# sessionStorage 对象
the different between localStorage is when the window is closed the data is clear
编辑 (opens new window)
上次更新: 2021/08/13, 23:21:49