使用JavaScript操作本地存儲(chǔ)
本地存儲(chǔ):localStorage 和 sessionStorage
在 JavaScript 中,localStorage 和 sessionStorage 都是 Web Storage API 的一部分,用于在瀏覽器中存儲(chǔ)數(shù)據(jù)。它們之間的主要區(qū)別是:
- localStorage:數(shù)據(jù)持久存儲(chǔ),即使瀏覽器關(guān)閉,數(shù)據(jù)依然存在。
- sessionStorage:數(shù)據(jù)僅在當(dāng)前會(huì)話中存在,當(dāng)瀏覽器窗口或標(biāo)簽頁(yè)關(guān)閉時(shí),數(shù)據(jù)會(huì)被清除。
這兩者都可以存儲(chǔ)字符串類(lèi)型的數(shù)據(jù),但可以通過(guò) JSON 序列化(JSON.stringify)和反序列化(JSON.parse)存儲(chǔ)和讀取對(duì)象、數(shù)組等復(fù)雜數(shù)據(jù)結(jié)構(gòu)。
基本使用方法
1. localStorage 示例
設(shè)置數(shù)據(jù):
localStorage.setItem('username', 'JohnDoe'); localStorage.setItem('age', '30');
獲取數(shù)據(jù):
const username = localStorage.getItem('username'); // 'JohnDoe' const age = localStorage.getItem('age'); // '30'
刪除數(shù)據(jù):
localStorage.removeItem('username');
清空所有數(shù)據(jù):
localStorage.clear();
數(shù)據(jù)持久性:
當(dāng)你關(guān)閉瀏覽器并重新打開(kāi)它時(shí),localStorage 中的數(shù)據(jù)依然存在。你可以在后續(xù)的頁(yè)面訪問(wèn)中讀取這些數(shù)據(jù)。
2. sessionStorage 示例
設(shè)置數(shù)據(jù):
sessionStorage.setItem('username', 'JaneDoe'); sessionStorage.setItem('age', '25');
獲取數(shù)據(jù):
const username = sessionStorage.getItem('username'); // 'JaneDoe' const age = sessionStorage.getItem('age'); // '25'
刪除數(shù)據(jù):
sessionStorage.removeItem('username');
清空所有數(shù)據(jù):
sessionStorage.clear();
數(shù)據(jù)生命周期:
sessionStorage 中的數(shù)據(jù)僅在當(dāng)前會(huì)話期間有效。關(guān)閉瀏覽器標(biāo)簽頁(yè)或窗口時(shí),數(shù)據(jù)會(huì)被清除。
實(shí)際項(xiàng)目中的應(yīng)用
我們可以將本地存儲(chǔ)用于各種應(yīng)用場(chǎng)景,例如用戶(hù)身份驗(yàn)證、用戶(hù)設(shè)置或購(gòu)物車(chē)狀態(tài)存儲(chǔ)等。
示例 1:用戶(hù)登錄狀態(tài)管理
假設(shè)你正在開(kāi)發(fā)一個(gè)簡(jiǎn)單的登錄頁(yè)面,當(dāng)用戶(hù)成功登錄時(shí),將用戶(hù)名和身份標(biāo)識(shí)存儲(chǔ)在 localStorage 中,后續(xù)頁(yè)面可以讀取這些數(shù)據(jù)來(lái)判斷用戶(hù)是否已經(jīng)登錄。
HTML(登錄頁(yè)面):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <h1>Login</h1> <form id="loginForm"> <input type="text" id="username" placeholder="Username" required> <input type="password" id="password" placeholder="Password" required> <button type="submit">Login</button> </form> <script src="login.js"></script> </body> </html>
JavaScript(login.js):
document.getElementById('loginForm').addEventListener('submit', function(event) { event.preventDefault(); const username = document.getElementById('username').value; const password = document.getElementById('password').value; // 假設(shè)進(jìn)行簡(jiǎn)單的用戶(hù)名和密碼驗(yàn)證 if (username === 'admin' && password === '1234') { // 登錄成功,存儲(chǔ)登錄信息到 localStorage localStorage.setItem('username', username); localStorage.setItem('isLoggedIn', 'true'); alert('Login successful!'); // 跳轉(zhuǎn)到歡迎頁(yè)面 window.location.href = 'welcome.html'; } else { alert('Invalid credentials'); } });
歡迎頁(yè)面(welcome.html):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome</title> </head> <body> <h1>Welcome</h1> <p id="welcomeMessage"></p> <script src="welcome.js"></script> </body> </html>
JavaScript(welcome.js):
// 在歡迎頁(yè)面加載時(shí),檢查用戶(hù)是否已登錄 window.onload = function() { const isLoggedIn = localStorage.getItem('isLoggedIn'); const username = localStorage.getItem('username'); if (isLoggedIn === 'true' && username) { document.getElementById('welcomeMessage').textContent = `Welcome, ${username}!`; } else { alert('You are not logged in'); window.location.href = 'login.html'; } };
解釋?zhuān)?/strong>
登錄頁(yè)面:用戶(hù)輸入用戶(hù)名和密碼進(jìn)行登錄,如果驗(yàn)證成功,將用戶(hù)名和登錄狀態(tài)存儲(chǔ)到 localStorage 中。
歡迎頁(yè)面:當(dāng)用戶(hù)訪問(wèn)歡迎頁(yè)面時(shí),首先檢查 localStorage 中是否存儲(chǔ)了登錄信息,如果有,則顯示歡迎信息;否則,跳轉(zhuǎn)到登錄頁(yè)面。
示例 2:實(shí)現(xiàn)一個(gè)簡(jiǎn)單的購(gòu)物車(chē)功能
在電商網(wǎng)站中,可以使用 localStorage 來(lái)存儲(chǔ)用戶(hù)的購(gòu)物車(chē)內(nèi)容,確保在用戶(hù)關(guān)閉瀏覽器后仍能保存購(gòu)物車(chē)的狀態(tài)。
HTML(購(gòu)物車(chē)頁(yè)面):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shopping Cart</title> </head> <body> <h1>Your Shopping Cart</h1> <div id="cartItems"></div> <button id="clearCart">Clear Cart</button> <script src="cart.js"></script> </body> </html>
JavaScript(cart.js):
// 添加商品到購(gòu)物車(chē) function addToCart(product) { let cart = JSON.parse(localStorage.getItem('cart')) || []; cart.push(product); localStorage.setItem('cart', JSON.stringify(cart)); } // 渲染購(gòu)物車(chē)內(nèi)容 function renderCart() { const cart = JSON.parse(localStorage.getItem('cart')) || []; const cartItemsContainer = document.getElementById('cartItems'); if (cart.length === 0) { cartItemsContainer.innerHTML = 'Your cart is empty.'; } else { cartItemsContainer.innerHTML = cart.map(item => `<p>${item.name} - $${item.price}</p>`).join(''); } } // 清空購(gòu)物車(chē) document.getElementById('clearCart').addEventListener('click', function() { localStorage.removeItem('cart'); renderCart(); }); // 頁(yè)面加載時(shí)渲染購(gòu)物車(chē) window.onload = renderCart; // 示例:添加一些商品到購(gòu)物車(chē) addToCart({ name: 'Laptop', price: 999 }); addToCart({ name: 'Headphones', price: 199 });
解釋?zhuān)?/strong>
購(gòu)物車(chē)功能:通過(guò) localStorage 存儲(chǔ)購(gòu)物車(chē)中的商品列表(使用 JSON.stringify 存儲(chǔ)數(shù)組,使用 JSON.parse 讀?。?/p>
頁(yè)面加載時(shí):當(dāng)頁(yè)面加載時(shí),檢查 localStorage 中是否有購(gòu)物車(chē)數(shù)據(jù),并渲染到頁(yè)面上。
清空購(gòu)物車(chē):點(diǎn)擊“清空購(gòu)物車(chē)”按鈕時(shí),刪除 localStorage 中的購(gòu)物車(chē)數(shù)據(jù),并刷新頁(yè)面。
總結(jié)
localStorage 和 sessionStorage 是用于在客戶(hù)端存儲(chǔ)數(shù)據(jù)的 Web API,可以存儲(chǔ)字符串、對(duì)象等數(shù)據(jù)。
localStorage 用于持久存儲(chǔ)數(shù)據(jù),頁(yè)面關(guān)閉后數(shù)據(jù)仍然存在;sessionStorage 用于會(huì)話存儲(chǔ),瀏覽器關(guān)閉或標(biāo)簽頁(yè)關(guān)閉時(shí)數(shù)據(jù)消失。
在實(shí)際項(xiàng)目中,常見(jiàn)的應(yīng)用包括用戶(hù)認(rèn)證、購(gòu)物車(chē)狀態(tài)、用戶(hù)設(shè)置等場(chǎng)景。
通過(guò)實(shí)際項(xiàng)目中的示例,您可以更清晰地理解如何使用這兩個(gè)存儲(chǔ)方法來(lái)管理瀏覽器中的數(shù)據(jù)。
到此這篇關(guān)于使用JavaScript操作本地存儲(chǔ)的文章就介紹到這了,更多相關(guān)JavaScript本地存儲(chǔ)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS實(shí)現(xiàn)簡(jiǎn)單獲取最近7天和最近3天日期的方法
這篇文章主要介紹了JS實(shí)現(xiàn)簡(jiǎn)單獲取最近7天和最近3天日期的方法,涉及javascript針對(duì)日期與時(shí)間的相關(guān)數(shù)值運(yùn)算與轉(zhuǎn)換操作技巧,需要的朋友可以參考下2018-04-04javascript獲得CheckBoxList選中的數(shù)量
javascript獲得CheckBoxList選中的數(shù)量(jQuery與Javascript對(duì)照學(xué)習(xí)/前臺(tái)與后臺(tái))2009-10-10javascript網(wǎng)頁(yè)關(guān)閉時(shí)提醒效果腳本
當(dāng)頁(yè)面載入和關(guān)閉時(shí)會(huì)出現(xiàn)一些提示信息的代碼。方便提醒用戶(hù),但不建議多用,讓人感到反感。2008-10-10完美兼容IE,chrome,ff的設(shè)為首頁(yè)、加入收藏及保存到桌面js代碼
這篇文章主要給大家分享了完美兼容IE,chrome,ff的設(shè)為首頁(yè)、收藏本站及保存到桌面js代碼,有需要的小伙伴參考下。2014-12-12JavaScript數(shù)組特性與實(shí)踐應(yīng)用深入詳解
這篇文章主要介紹了JavaScript數(shù)組特性與實(shí)踐應(yīng)用,較為深入而詳細(xì)的分析了javascript數(shù)組的功能、屬性、使用方法及操作注意事項(xiàng),需要的朋友可以參考下2018-12-12微信小程序數(shù)據(jù)監(jiān)聽(tīng)器使用實(shí)例詳解
這篇文章主要介紹了微信小程序數(shù)據(jù)監(jiān)聽(tīng)器使用實(shí)例,數(shù)據(jù)監(jiān)聽(tīng)器用于監(jiān)聽(tīng)和響應(yīng)任何屬性和數(shù)據(jù)字段的變化,從而執(zhí)行特定的操作。它的作用類(lèi)似于vue中的watch偵聽(tīng)器2023-04-04uniapp的webview實(shí)現(xiàn)左滑返回上一個(gè)頁(yè)面操作方法
uniapp默認(rèn)左滑是關(guān)閉整個(gè)webview,而不是關(guān)閉當(dāng)前頁(yè),本文給大家介紹uniapp的webview實(shí)現(xiàn)左滑返回上一個(gè)頁(yè)面操作方法,感興趣的朋友一起看看吧2023-12-12js 分頁(yè)全選或反選標(biāo)識(shí)實(shí)現(xiàn)代碼
分頁(yè)全選或反選標(biāo)識(shí) 對(duì)多選按鈕操作。 批量全選添加、批量移除。 行單選添加、移除。 分頁(yè)之后(全選或不選)狀態(tài)標(biāo)識(shí)依然存在2011-08-08JavaScript中Object.freeze()和Object.seal()的使用
Object.freeze()和Object.seal()是JavaScript中用于控制對(duì)象可變性的兩個(gè)方法,本文就詳細(xì)的介紹一下這兩種方法,感興趣的可以了解一下2024-09-09