iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0

1.甚麼是本地儲存

這個功能可以讓你把資料存在使用者的瀏覽器中,就算重新整理頁面或是關掉再打開,資料都還在
使用者登入之後一旦重新整理就要再輸入一次帳號密碼或是網頁上有深色模式,但是換一頁就又回到亮色之類的,這些問題超級惱人!
解決這些問題,瀏覽器提供了Web Storage API,localStoragesessionStorage

2.localStorage與sessionStorage

特性 localStorage sessionStorage
資料存活時間 永久(除非手動刪除) 頁面關閉後就清掉
範圍 同一個網域 同一個頁面分頁
常見用途 偏好設定、登入狀態、購物車 臨時表單資料、單次瀏覽紀錄

3.用法

兩者用法完全一樣,差別只在於存活時間,所以就按照需求來決定要使用哪一個
接下來就是操作資料的辦法:

(1) 存資料:setItem

localStorage.setItem("username", "Alice");
sessionStorage.setItem("theme", "dark");

(2) 取資料:getItem

const user = localStorage.getItem("username");
console.log(user); // "Alice"

(3) 刪除資料:removeItem

localStorage.removeItem("username");

(4) 清空所有資料:clear

localStorage.clear(); // 清除所有 localStorage

4.JSON

由於Web Storage只能存字串,如果要存物件或陣列,就需要用到JSON.stringifyJSON.parse

儲存物件

const user = { name: "Alice", age: 20 };
localStorage.setItem("user", JSON.stringify(user));

讀取物件

const savedUser = JSON.parse(localStorage.getItem("user"));
console.log(savedUser.name); // Alice

這樣就能安全地存取結構化資料

小練習

寫一個簡單的「深色模式」切換,並記住使用者的偏好設定

<button id="toggleTheme">切換主題</button>
<script>
  const body = document.body;
  const toggleBtn = document.querySelector("#toggleTheme");

  // 初始化:如果有記錄就套用
  if (localStorage.getItem("theme") === "dark") {
    body.style.background = "black";
    body.style.color = "white";
  }

  toggleBtn.addEventListener("click", () => {
    if (localStorage.getItem("theme") === "dark") {
      localStorage.setItem("theme", "light");
      body.style.background = "white";
      body.style.color = "black";
    } else {
      localStorage.setItem("theme", "dark");
      body.style.background = "black";
      body.style.color = "white";
    }
  });
</script>

整理一下今天學到的內容:localStorage可以永久保存,跨頁面都可使用,sessionStorage則是頁面關閉就消失,而Web Storage只能存字串,如果儲存物件與陣列需要用JSON.stringify/JSON.parse


上一篇
Day19:計時器-setTimeout與setInterval
下一篇
Day21:AJAX與Fetch API
系列文
30天入門Java Script21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言