本地存储
特性
- 数据存储在浏览器中,刷新不丢失
- 容量比较大,sessionStorage约5M,localStorage约20M
- 只能存储字符串,可以将对象JSON.stringify() 编码后存储
window.sessionStorage
- 生命周期为关闭浏览器窗口
- 在同一个窗口(页面)下数据可以共享
- 以键值对的形式存储使用
sessionStorage.setItem(key,value)
set.addEventListener('click', function() {
var val = ipt.value;
sessionStorage.setItem('uname', val);
sessionStorage.setItem('pwd', val);
});
get.addEventListener('click', function() {
console.log(sessionStorage.getItem('uname'));
});
remove.addEventListener('click', function() {
sessionStorage.removeItem('uname');
});
del.addEventListener('click', function() {
sessionStorage.clear();
});
- 存储的内容可以使用浏览器的调试窗口的application里的storage查看
window.localStorage
- 生命周期永久生效,除非手动删除,否则关闭页面也会存在
- 可以多窗口共享(同一浏览器共享)
- 以键值对的形式存储使用
set.addEventListener('click', function() {
var val = ipt.value;
localStorage.setItem('username', val);
})
get.addEventListener('click', function() {
console.log(localStorage.getItem('username'));
})
remove.addEventListener('click', function() {
localStorage.removeItem('username');
})
del.addEventListener('click', function() {
localStorage.clear();
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="username"> <input type="checkbox" name="" id="remember"> 记住用户名
<script>
var username = document.querySelector('#username');
var remember = document.querySelector('#remember');
if (localStorage.getItem('username')) {
username.value = localStorage.getItem('username');
remember.checked = true;
}
remember.addEventListener('change', function() {
if (this.checked) {
localStorage.setItem('username', username.value)
} else {
localStorage.removeItem('username');
}
})
</script>
</body>
|