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>