HTML5 web 存储,一个比cookie更好的本地存储方式。
localStorage - 用于长久保存整个网站的数据,保存的数据没有过期时间,直到手动去除。
sessionStorage - 用于临时保存同一窗口(或标签页)的数据,在关闭窗口或标签页之后将会删除这些数据。
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>WEB存储-localStorage对象</h3>
<div id="result"></div>
<script>
localStorage.bname='bolala';//设置在数据
document.getElementById('result').innerHTML = `姓名:${localStorage.bname}`;
localStorage.setItem('tom','man');//保存数据
localStorage.setItem('jhon','woman');
var c=localStorage.getItem('tom');//得到数据
console.log(c);
localStorage.removeItem('jhon');//删除一个数据
localStorage.clear();//删除所有数据
</script>
</body>
</html>
保存数据 | localStorage.setItem(key,value); |
读取数据 | localStorage.getItem(key); |
删除单个数据 | localStorage.removeItem(key); |
删除所有数据 | localStorage.clear(); |
得到某个索引的key | localStorage.key(index); |
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="result"></div>
<input type="button" value="点击我" id="btn">
<script>
var c=localStorage.count=0;
btn.onclick=function () {
c=parseInt(c)+1;
document.getElementById('result').innerHTML=`点击了${c}次`
}
</script>
</body>
</html>
sessionStorage的和这个超不多
一个注册登录的练习
index.html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<header>
<a href="login.html" target="_blank" rel="external nofollow" >登陆</a>
</header>
<script>
if (sessionStorage.name) {
document.querySelector('header').innerHTML=`欢迎回来${sessionStorage.name}  <a href="logout.html" target="_blank" rel="external nofollow" >退出登录</a>`
}
</script>
</body>
</html>
login.html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
昵称:<input type="text" id="cname">
密码:<input type="text" id="pwd">
<input type="submit" value="提交" id="btn">
<script>
if (sessionStorage.name) {
location.href='index.html'
}
btn.onclick=function(){
sessionStorage.name=cname.value;
sessionStorage.pwd=pwd.value;
alert('登陆成功,三秒后跳转');
setTimeout(function () {
location.href='index.html'
},3000)
}
</script>
</body>
</html>
logout.html
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>推出成功,三秒后返回</h3>
<script>
sessionStorage.removeItem('name');
sessionStorage.removeItem('pwd');
setTimeout(function () {
location.href='index.html'
},3000)
</script>
</body>
</html>