本地存储---localStorage和sessionStorage
区别:
cookie
:文本、大小4kb、数量限制为50条、会话级(非永久存储)、不允许跨域、跟随http发送至服务器
localStorage
:文本、大小5M、永久存储、不允许跨域、不跟随http发送至服务器
sessionStorage
:文本、大小5M、会话级(非永久存储)、不允许跨域、不跟随http发送至服务器
localStorage
属性:
localStorage.key=value 设置,修改
localStorage.key; 获取
delete localStorage.key 删除 localStorage.key = undefined
for-in localStorage 枚举 批量删除
//设置、修改
localStorage.name = "admin";
localStorage.age = 18;
//获取
console.log(localStorage.name); //admin
console.log(localStorage.age); //18
//删除
delete localStorage.age;
//枚举、批量删除
for(var i in localStorage){
console.log(i)
}
方法:
localStorage.setItem(key,value) 设置、修改
localStorage.getItem(key) 获取
localStorage.removeItem(key) 删除一个
localStorage.clear() 删除所有 ×
//设置、修改
localStorage.setItem("name","root");
localStorage.setItem("like","ball");
//获取
console.log(localStorage.getItem("name"))
console.log(localStorage.getItem("like"))
//删除一个
localStorage.removeItem("name");
//删除所有
localStorage.clear()
事件:
window.onstorage 检测key 发生了变化,事件对象
ev.key 返回 变化的key
ev.newValue 变化后的值
ev.oldValue 变化前的值
当点击后当前页面没有出现1,反而打开一个相同页面,点击这个页面会在另一个页面显示1
document.onclick = function(){
localStorage.test = Math.random();
}
onstorage = function(){
console.log(1)
}
注:写到localStorage里面的都是字符,要用JSON进行转化
sessionStorage
与localStorage方法一样
属性:
sessionStorage.key=value 设置,修改
sessionStorage.key; 获取
delete sessionStorage.key 删除 sessionStorage.key = undefined
for-in sessionStorage 枚举 批量删除
方法:
sessionStorage.setItem(key,value) 设置、修改
sessionStorage.getItem(key) 获取
sessionStorage.removeItem(key) 删除一个
sessionStorage.clear() 删除所有 ×
注:sessionStorage关闭页面后存储也相应的消失,但localStorage不会