HTML5中 Web Storage 的出现,主要是为了弥补使用 Cookie 作为本地存储的不足。Cookie 存储的数据量非常小,而且数据会自动携带到请求头里,但服务器端可能并不关心这些数据,所以会造成带宽的浪费。
Web Storage 提供了两个存储对象:localStorage 和 sessionStorage。
知识点:
window.sessionStorage//会话存储
window.localStorage//本地保存数据
sessionStorage与localStorage的区别:
1.localStorage:永久存储
sessionStorage:当浏览器窗口关闭时失效
2.localStorage:对于同源窗口可以共享
sessionStorage:不同的窗口不共享
setItem(key, value) 设置存储内容
getItem(key) 读取存储内容
removeItem(key) 删除键值为key的存储内容
clear() 清空所有存储内容
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
outline: none;
}
.box{
width: 300px;
height: 250px;
margin: 100px auto;
text-align: center;
background:pink ;
overflow: hidden;
}
input[type="text"],input[type="password"]{
width: 190px;
height: 30px;
display: block;
margin-left:50px;
padding-left: 10px;
}
input[type="text"]:first-child{
margin-top: 50px;
}
input[type="button"]{
width: 60px;
height: 30px;
border: none;
}
</style>
</head>
<body>
<div class="box">
<input type="text" id="name" placeholder="input your name"/><br />
<input type="password" id="pw" placeholder="input your password"/><br />
<input type="button" value="resiger" />
<input type="button" value="login" />
</div>
<script>
var txt=document.querySelectorAll("input");
var userName=txt[0];
var password=txt[1];
var resiger=txt[2];
var login=txt[3];
var jsonInfo=JSON.parse(window.sessionStorage.getItem("info")||"[]");//读取存储内容
resiger.οnclick=function(){
var n=userName.value;
var pw=password.value;
if(n.trim()==""||pw.trim()==""){
alert("请完善信息!!");
return;
}
var json={
"name":n,
"password":pw
};
for(var i=0;i<jsonInfo.length;i++){
console.log(jsonInfo[i].name);
if(n==jsonInfo[i].name){
alert("用户已存在!!!");
return;
}
}
jsonInfo.push(json);
window.sessionStorage.setItem("info",JSON.stringify(jsonInfo));//设置存储内容
alert("注册成功!!!");
}
login.οnclick=function(){
var n=userName.value;
var pw=password.value;
for(var i=0;i<jsonInfo.length;i++){
console.log(jsonInfo[i].name);
if(n==jsonInfo[i].name&&pw==jsonInfo[i].password){
alert("登录成功!!!");
return;
}
alert("密码与用户名不匹配!!!");
}
}
</script>
</body>
</html>
在 setItem
时,可能会达到大小限制,最好加上错误捕捉:
try {
localStorage.setItem(key, value);
} catch(e) {
if (isQuotaExceeded(e)) {
// Storage full, maybe notify user or do some clean-up
}
}
function isQuotaExceeded(e) {
var quotaExceeded = false;
if (e) {
if (e.code) {
switch (e.code) {
case 22:
quotaExceeded = true;
break;
case 1014:
// Firefox
if (e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
quotaExceeded = true;
}
break;
}
} else if (e.number === -2147024882) {
// Internet Explorer 8
quotaExceeded = true;
}
}
return quotaExceeded;
}