HTML/JavaScript本地存储:跨页编辑、过期设置及窗口清除需求
Hey there! Let's start by fixing a few typos in your initial code that would break the data passing, then we'll tackle each of your requirements step by step.
Step 1: Fix Initial Code Issues
In your page1.html's passvalues() function, there are two variable name mistakes that would cause errors:
- You tried to store
lastnameusing an undefined variable (you named the input valuename, notlastname) - You attempted to store
colorvaluewithselectcolor, but the variable is actuallyselectext
Here's the corrected passvalues() function for page1:
function passvalues(){ var firstname = document.getElementById("first").value; var lastname = document.getElementById("last").value; // Fixed variable name var colorvalue = document.getElementById("mycolor").value; // Simplified variable name localStorage.setItem("firstname", firstname); localStorage.setItem("lastname", lastname); localStorage.setItem("colorvalue", colorvalue); return true; }
Step 2: Sync Page2 Edits to Page1
To sync edits from page2 back to page1, we'll use the storage event—this event fires on all open same-origin pages when localStorage is modified.
Update Page1 to Listen for Changes
Add this script to page1.html (place it before the closing </body> tag) to listen for storage updates and refresh the input fields:
// Listen for localStorage changes from other pages window.addEventListener('storage', function(e) { // Update the DOM only if the changed key is one of our data keys if (e.key === 'firstname') { document.getElementById("first").value = e.newValue; } else if (e.key === 'lastname') { document.getElementById("last").value = e.newValue; } else if (e.key === 'colorvalue') { document.getElementById("mycolor").value = e.newValue; } });
Add Editing Functionality to Page2
Modify page2.html to add editable fields and save changes to localStorage (this will trigger the storage event in page1 automatically):
<html> <head> <style> .edit-fields { display: none; margin-top: 20px; } </style> </head> <body> <center> <h1>page2</h1> <hr/> Welcome.. <span id="resultfirst"></span><br> Welcome.. <span id="resultlast"></span><br> Welcome.. <span id="resultcolor"></span><br> <button id="edit">Edit</button> <!-- Editable fields (hidden by default) --> <div class="edit-fields"> <input type="text" id="edit-first" placeholder="First name"><br> <input type="text" id="edit-last" placeholder="Last name"><br> <select id="edit-color"> <option>Color</option> <option>Red</option> <option>Blue</option> <option>Purple</option> <!-- Fixed typo from "Purlpe" --> <option>Green</option> </select><br> <button id="save">Save Changes</button> </div> <script> // Load initial data const firstname = localStorage.getItem("firstname"); const lastname = localStorage.getItem("lastname"); const colorvalue = localStorage.getItem("colorvalue"); document.getElementById("resultfirst").innerHTML = firstname; document.getElementById("resultlast").innerHTML = lastname; document.getElementById("resultcolor").innerHTML = colorvalue; // Populate edit fields when Edit button is clicked document.getElementById("edit").addEventListener('click', function() { document.querySelector('.edit-fields').style.display = 'block'; document.getElementById("edit-first").value = firstname; document.getElementById("edit-last").value = lastname; document.getElementById("edit-color").value = colorvalue; }); // Save changes to localStorage document.getElementById("save").addEventListener('click', function() { const newFirst = document.getElementById("edit-first").value; const newLast = document.getElementById("edit-last").value; const newColor = document.getElementById("edit-color").value; localStorage.setItem("firstname", newFirst); localStorage.setItem("lastname", newLast); localStorage.setItem("colorvalue", newColor); // Update page2's display document.getElementById("resultfirst").innerHTML = newFirst; document.getElementById("resultlast").innerHTML = newLast; document.getElementById("resultcolor").innerHTML = newColor; // Hide edit fields document.querySelector('.edit-fields').style.display = 'none'; }); </script> </center> </body> </html>
Step 3: Add Expiration to localStorage
LocalStorage doesn't have built-in expiration, so we'll store data along with an expiration timestamp. We'll create helper functions to handle storing, checking, and cleaning up expired data.
Update Page1's Storage Logic
Replace the passvalues() function in page1.html with these helper functions and updated logic:
// Helper to store data with expiration (in milliseconds) function setWithExpiry(key, value, ttl) { const now = new Date(); const item = { value: value, expiry: now.getTime() + ttl, }; localStorage.setItem(key, JSON.stringify(item)); } // Helper to get data (and delete if expired) function getWithExpiry(key) { const itemStr = localStorage.getItem(key); if (!itemStr) { return null; } const item = JSON.parse(itemStr); const now = new Date(); // If expired, delete and return null if (now.getTime() > item.expiry) { localStorage.removeItem(key); return null; } return item.value; } function passvalues(){ var firstname = document.getElementById("first").value; var lastname = document.getElementById("last").value; var colorvalue = document.getElementById("mycolor").value; // Set expiration to 5 minutes (5*60*1000 ms) - adjust as needed const expiryTime = 5 * 60 * 1000; setWithExpiry("firstname", firstname, expiryTime); setWithExpiry("lastname", lastname, expiryTime); setWithExpiry("colorvalue", colorvalue, expiryTime); return true; }
Update Page2's Data Loading & Saving Logic
Modify the data loading part in page2.html to use the expiration helpers, and update the save function:
// Add helper functions first function getWithExpiry(key) { const itemStr = localStorage.getItem(key); if (!itemStr) { return null; } const item = JSON.parse(itemStr); const now = new Date(); if (now.getTime() > item.expiry) { localStorage.removeItem(key); return null; } return item.value; } function setWithExpiry(key, value, ttl) { const now = new Date(); const item = { value: value, expiry: now.getTime() + ttl, }; localStorage.setItem(key, JSON.stringify(item)); } // Load initial data with expiration check const firstname = getWithExpiry("firstname"); const lastname = getWithExpiry("lastname"); const colorvalue = getWithExpiry("colorvalue"); // Update display - show default text if data is expired document.getElementById("resultfirst").innerHTML = firstname || "No data (expired)"; document.getElementById("resultlast").innerHTML = lastname || "No data (expired)"; document.getElementById("resultcolor").innerHTML = colorvalue || "No data (expired)"; // ... (keep the edit button logic) // Update save button handler to use setWithExpiry document.getElementById("save").addEventListener('click', function() { const newFirst = document.getElementById("edit-first").value; const newLast = document.getElementById("edit-last").value; const newColor = document.getElementById("edit-color").value; const expiryTime = 5 * 60 * 1000; // 5 minutes setWithExpiry("firstname", newFirst, expiryTime); setWithExpiry("lastname", newLast, expiryTime); setWithExpiry("colorvalue", newColor, expiryTime); // Update page2's display document.getElementById("resultfirst").innerHTML = newFirst; document.getElementById("resultlast").innerHTML = newLast; document.getElementById("resultcolor").innerHTML = newColor; // Hide edit fields document.querySelector('.edit-fields').style.display = 'none'; });
Step 4: Clear localStorage on Refresh/Close
Add this script to both page1 and page2 (place it before the closing </body> tag) to clear your data when the page is refreshed or closed:
// Clear localStorage when page is refreshed or closed window.addEventListener('beforeunload', function() { // Clear specific keys (or use localStorage.clear() to delete everything) localStorage.removeItem("firstname"); localStorage.removeItem("lastname"); localStorage.removeItem("colorvalue"); });
That's all! Each requirement is now implemented:
- Page2 edits sync to page1 in real-time via the
storageevent - LocalStorage data has a configurable expiration time and gets cleaned up automatically
- Data is cleared immediately when the page is refreshed or closed
内容的提问来源于stack exchange,提问作者Scofield

