localStorage
那 localStorage 就是非常適合的選擇!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Save Input on Reload</title>
</head>
<body>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="comments">Comments:</label>
<textarea id="comments" name="comments" rows="4" cols="50"></textarea>
<br><br>
<label for="email">Email (uses data-save attribute):</label>
<input type="email" id="email" data-save-input="email_field">
<br><br>
<button id="clearStorage">Clear Saved Inputs</button>
<script>
// JavaScript 邏輯會放在這裡
</script>
</body>
</html>
即時儲存 (on input event): 使用者每輸入一個字元就儲存。失去焦點時儲存 (on change or blur event): 使用者輸入完成,焦點離開輸入框時儲存。頁面卸載前儲存 (on beforeunload event): 作為最後的保險。
document.addEventListener('DOMContentLoaded', () => {
const usernameInput = document.getElementById('username');
const commentsTextarea = document.getElementById('comments');
const emailInput = document.getElementById('email'); // 使用 data-save-input 的例子
const clearButton = document.getElementById('clearStorage');
// --- 1. 頁面載入時恢復儲存的內容 ---
function loadSavedData() {
const savedUsername = localStorage.getItem('savedUsername');
if (savedUsername !== null) { // 檢查是否有儲存的值
usernameInput.value = savedUsername;
}
const savedComments = localStorage.getItem('savedComments');
if (savedComments !== null) {
commentsTextarea.value = savedComments;
}
// 處理帶有 data-save-input 屬性的輸入框
const inputsToSave = document.querySelectorAll('[data-save-input]');
inputsToSave.forEach(input => {
const storageKey = input.dataset.saveInput; // 獲取 data-save-input 的值作為 key
const savedValue = localStorage.getItem(storageKey);
if (savedValue !== null) {
input.value = savedValue;
}
});
}
loadSavedData(); // 載入頁面時執行
// --- 2. 當輸入框內容改變時儲存 ---
// 方法 A: 針對特定 ID 的輸入框
usernameInput.addEventListener('input', () => {
localStorage.setItem('savedUsername', usernameInput.value);
});
commentsTextarea.addEventListener('input', () => {
localStorage.setItem('savedComments', commentsTextarea.value);
});
// 方法 B: 針對所有帶有特定 data 屬性的輸入框 (更通用)
// 你也可以使用 class 來選取
document.querySelectorAll('[data-save-input]').forEach(input => {
const storageKey = input.dataset.saveInput;
input.addEventListener('input', () => {
localStorage.setItem(storageKey, input.value);
});
});
// --- (可選) 3. 清除儲存的內容 ---
clearButton.addEventListener('click', () => {
// 逐個移除,或者如果你知道所有 key,可以迴圈移除
localStorage.removeItem('savedUsername');
localStorage.removeItem('savedComments');
// 清除所有 data-save-input 的項目
const inputsToSave = document.querySelectorAll('[data-save-input]');
inputsToSave.forEach(input => {
localStorage.removeItem(input.dataset.saveInput);
});
// 清空輸入框的值 (可選)
usernameInput.value = '';
commentsTextarea.value = '';
emailInput.value = '';
alert('Saved input values have been cleared!');
// 如果你想清除所有 localStorage 中的內容 (請謹慎使用,這會清除該網域下所有 localStorage)
// localStorage.clear();
});
// --- (可選) 4. 頁面卸載前再次嘗試儲存 (作為保險) ---
// 有些瀏覽器可能對 beforeunload 中的操作有限制
// window.addEventListener('beforeunload', () => {
// localStorage.setItem('savedUsername', usernameInput.value);
// localStorage.setItem('savedComments', commentsTextarea.value);
// const inputsToSave = document.querySelectorAll('[data-save-input]');
// inputsToSave.forEach(input => {
// localStorage.setItem(input.dataset.saveInput, input.value);
// });
// });
});
DOMContentLoaded 事件: 確保在整個 HTML 文件都載入並解析完畢後才執行 JavaScript 程式碼。localStorage.getItem('key') : 從 localStorage 中讀取指定 key 的值。如果該 key 不存在,則返回 null。localStorage.setItem('key', 'value') : 將一個鍵值對儲存到 localStorage。注意:localStorage 只能儲存字串。 如果你想儲存物件或陣列,需要先用 JSON.stringify() 轉換成字串,讀取時再用 JSON.parse() 轉回來。但對於輸入框的值 (通常是字串),直接儲存即可。localStorage.removeItem('key') : 從 localStorage 中移除指定的 key 及其對應的值。localStorage.clear() : 清除該網域下 localStorage 中的所有資料。請謹慎使用! input 事件: 當 <input> 或 <textarea> 的 value 改變時觸發,非常適合即時保存。data-save-input 屬性 (可選的通用方法): 在 HTML 元素上添加 data-save-input="your_unique_key"。 JavaScript 中選取所有帶有 data-save-input 屬性的元素。 使用 element.dataset.saveInput 來獲取 your_unique_key 作為 localStorage 的鍵。 這樣你就不需要為每個輸入框單獨寫恢復和儲存的邏輯了。
簡單易用。 儲存容量比 Cookie 大 (通常 5-10MB)。 數據不會隨 HTTP 請求自動發送到伺服器,減少了不必要的流量。
安全性: localStorage 中的資料可以被同網域下的任何 JavaScript 程式碼讀取,所以不要用它來儲存敏感資訊 (如密碼、信用卡號等)。同步操作: localStorage 的讀寫操作是同步的,如果進行非常頻繁或大量的讀寫,理論上可能會對頁面效能造成微小影響,但對於儲存幾個輸入框內容來說,幾乎可以忽略不計。使用者清除: 使用者可以透過瀏覽器設定清除 localStorage 的資料。
留言
張貼留言