storage:
sessionStorage
session临时回话,从页面打开到页面关闭的时间段
窗口的临时存储,页面关闭,本地存储消失
localStorage
永久存储 (可以手动删除数据)
Storage的特点
存储量限制 (
5M )
客户端完成,不会请求服务器处理
sessionStorage数据是不共享、 localStorage共享
window.sessionStorage
window.localStorage
setItem():
设置数据,key\
value类型,类型都是字符串
可以用获取属性的形式操作
getItem():
获取数据,通过key来获取到相应的
value
removeItem():
删除数据,通过key来删除相应的
value
clear():
删除全部存储的值
模拟登陆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document
</title>
<style type="text/css">
* {margin: 0; padding: 0;}
a {text-decoration: none;}
ul,li {list-style: none;}
body {font-family: "Microsoft yahei";}
.login {display: none;}
</style>
</head>
<body>
<input type="text" id="user">
<input type="text" id="password">
<input type="button" id='login' value='登录'>
<div class="login"></div>
<input type="button" id='exit' value='退出'>
<script>
var User = document.querySelector('.login');
if(window.localStorage.getItem('user')){
login.style.display = "none";
User.innerHTML = "你好,"+ window.localStorage.getItem('user');
User.style.display = 'inline-block';
user.value = window.localStorage.getItem('user');
}
login.onclick = function (e) {
console.log(window.localStorage);
window.localStorage.setItem('user',user.value);
alert('登录成功');
};
exit.onclick = function () {
window.localStorage.removeItem('user');
}
</script>
</body>
</html>
多个同一页面数据共享
服务器下:
监听存储事件:
当数据有修改或删除的情况下,就会触发storage事件
在对数据进行改变的窗口对象上是不会触发的
Key : 修改或删除的key值,如果调用
clear(),key为
null
newValue : 新设置的值,如果调用removeStorage(),key为
null
oldValue : 调用改变前的
value值
storageArea : 当前的storage对象
url : 触发该脚本变化的文档的url
注:session同窗口才可以,例子:iframe操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document
</title>
<style type="text/css">
* {margin: 0; padding: 0;}
a {text-decoration: none;}
ul,li {list-style: none;}
body {font-family: "Microsoft yahei";}
</style>
</head>
<body>
<input type="checkbox" value='芒果'/>芒果
<input type="checkbox" value='香蕉'/>香蕉
<input type="checkbox" value='西瓜'/>西瓜
<input type="checkbox" value='橘子'/>橘子
<input type="checkbox" value='桃子'/>桃子
<script type="text/javascript">
var Input = document.querySelectorAll('input');
for (var i = 0; i < Input.length; i++) {
Input[i].onclick = function (e) {
if( this.checked ){
window.localStorage.setItem('set',this.value);
console.log(1);
}else{
window.localStorage.setItem('no',this.value);
console.log(2);
}
}
}
window.addEventListener('storage',function (e) {
var e = e||window.event;
console.log(1);
if(e.key == 'set'){
for (var i = 0; i < Input.length; i++) {
if(e.newValue == Input[i].value){
Input[i].checked = true;
}
}
}else if(e.key == 'no'){
for (var i = 0; i < Input.length; i++) {
if(e.newValue == Input[i].value){
Input[i].checked = false;
}
}
}
})
</script>
</body>
</html>