浏览器本地储存
浏览器通过window.sessionStorage和window.localStorage属性来实现本地存储机制
window.localStorage
localStorage.setItem
localStorage.setItem('name','msg')
localStorage.setItem('name','对象')
使用localStorage.setItem函数可以往本地储存中存入字符串或者对象
存入对象时要用JSON.stringify(name)将数据变成对象
localStorage.getItem
localStorage.getItem('name')获取name名称的本地浏览信息
localStorage.removeItem
localStorage.removeItem(name)删除name名称的本地浏览信息
localStorage.clear()
localStorage.clear()删除所有的本地浏览信息
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>localStorage</h2> <button onclick="saveData()">点我保存一个数据</button> <button onclick="readData()">点我读取一个数据</button> <button onclick="deleteData()">点我删除一个数据</button> <button onclick="deleteAllData()">点我清空数据</button> <script type="text/javascript"> let p = {name:'gugu',age:18} function saveData(){ localStorage.setItem('msg','hello!!') localStorage.setItem('person',JSON.stringify(p)) } function readData(){ console.log(localStorage.getItem('msg')) const res = localStorage.getItem('person') console.log(JSON.parse(res)) } function deleteData(){ localStorage.removeItem('msg') } function deleteAllData(){ localStorage.clear() } </script> </body> </html>
window.sessionStorage
session和local一样
sessionStorage内容随着浏览器窗口关闭而消失
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>sessionStorage</h2> <button onclick="saveData()">点我保存一个数据</button> <button onclick="readData()">点我读取一个数据</button> <button onclick="deleteData()">点我删除一个数据</button> <button onclick="deleteAllData()">点我清空数据</button> <script type="text/javascript"> let p = {name:'gugu',age:18} function saveData(){ sessionStorage.setItem('msg','hello!!') sessionStorage.setItem('person',JSON.stringify(p)) } function readData(){ console.log(sessionStorage.getItem('msg')) const res = sessionStorage.getItem('person') console.log(JSON.parse(res)) } function deleteData(){ sessionStorage.removeItem('msg') } function deleteAllData(){ sessionStorage.clear() } </script> </body> </html>
总结
1.存储大小一般支持5MB左右(不同浏览器会不一样)标签:function,储存,浏览器,name,sessionStorage,setItem,localStorage,getItem,day78 From: https://www.cnblogs.com/GUGUZIZI/p/17162954.html
2.浏览器通过window.sessionStorage和window.localStorage属性来实现本地存储机制
3.相关API:
xxxxxStorage.setItem('key','value')
将键值添加到存储中,如果键名存在,更新对应的值
xxxxxStorage.getItem('key','value')
返回键名的值
xxxxxStorage.removeItem('key')
把该键名从存储中删除
xxxxxStorage.clear()
清空所有数据
4.备注:
sessionStorage内容随着浏览器窗口关闭而消失
localStorage需要手动清除才会消失
xxxxxStorage.getItem('key','value')如果value获取不到,返回值是null
JSON.parse(null)的结果还是null