HTML5的本地存储
16lz
2021-01-22
HTML5的本地存储分为永久性的本地存储和会话性的本地存储。
会话性本地存储sessionStorage
存储在sessionStorage中的数据首先是Key-Value形式的,另外就是它跟浏览器当前会话相关,当会话结束后,数据会自动清除,跟未设置过期时间的Cookie类似。
sessionStorage对本地存储的相关操作:
- setItem(key,value):添加本地存储数据,键值对形式。
- getItem(key):通过key获取相应的Value。
- removeItem(key):通过key删除本地数据。
- clear():清空数据。
// sessionStorage:临时性本地存储
// 1.临时 页面关闭 存储消失
// 2.同域名下本页面能用 其他页面不可见
//形式:名值对
//存储数据
set.onclick=function()
{
sessionStorage.setItem("name","xiaoming");
sessionStorage.setItem("age","18");
sessionStorage.setItem("sex","男");
}
//获取数据
get.onclick=function()
{
sessionStorage.getItem("name");
}
//移除数据
remove.onclick=function()
{
sessionStorage.removeItem("name");//逐条删
sessionStorage.clear();//删除全部
}
//获取key名
key.onclick=function()
{
alert(sessionStorage.key(0));
}
//获取本地存储length
length.onclick=function()
{
alert(sessionStorage.length);
}
永久性本地存储localStorage
在最新的JS的API中增加了localStorage对象,以便于用户存储永久存储的Web端的数据。而且数据不会随着Http请求发送到后台服务器,而且存储数据的大小几乎不用考虑。
localStorage对本地存储的相关操作:
- setItem(key,value):添加本地存储数据,键值对形式。
- getItem(key):通过key获取相应的Value。
- removeItem(key):通过key删除本地数据。
clear():清空数据。
// localStorage:临时性本地存储
// 1.临时 页面关闭 存储消失
// 2.同域名下本页面能用 其他页面不可见
//形式:名值对
//存储数据
set.onclick=function()
{
localStorage.setItem("name","xiaoming");
localStorage.setItem("age","18");
localStorage.setItem("sex","男");
}
//获取数据
get.onclick=function()
{
localStorage.getItem("name");
}
//移除数据
remove.onclick=function()
{
localStorage.removeItem("name");//逐条删
localStorage.clear();//删除全部
}
//获取key名
key.onclick=function()
{
alert(localStorage.key(0));
}
//获取本地存储length
length.onclick=function()
{
alert(localStorage.length);
}
更多相关文章
- 使用html5中的base64数据播放音频。
- 从html文档中解析数据()[重复]
- 对于表格数据,什么渲染更快,CSS或?
- ajax提交含有html数据时的处理方法
- html5统计数据上报API:SendBeacon
- 上传文件,那么form中用来接收文件的数据成员是什么类型?
- 请问json文件在html head中以script的形式导入了,怎样读取这个jso
- 服务器数据库系列 - 日志系列 - Nginx日志
- 指导我优化我的PHP代码,用数组中的空数据填充缺失值