如何实现多次存储搜索名称至localStorage,返回页面仍能全部展示?
Got it, let's sort out this localStorage issue for you! The problem right now is that you're overwriting the same name key every time you search—so each new entry replaces the old one. Instead, we need to store all your search names in an array, so we can keep adding new entries without losing any previous ones.
Step 1: Update the Storage Logic
Instead of saving a single name to the same key, we'll store an array of all searched names. Here's how to adjust your save code:
// When you get the new search name (e.g., from currentWeather.name) const newSearchName = currentWeather.name; // Fetch existing names from localStorage, or start with an empty array if none exist let savedNames = JSON.parse(localStorage.getItem("searchNames")) || []; // Optional: Skip duplicates if you don't want the same name saved multiple times if (!savedNames.includes(newSearchName)) { savedNames.push(newSearchName); } // Save the updated array back to localStorage (we convert it to a string because localStorage only stores strings) localStorage.setItem("searchNames", JSON.stringify(savedNames));
Step 2: Update the Display Logic
Now we'll fetch the full array of names and loop through it to show all entries:
// Run this when the page loads or when you want to display your search history const savedNames = JSON.parse(localStorage.getItem("searchNames")) || []; const recordContainer = document.getElementById("record"); // Clear existing content first (prevents duplicate displays if you run this multiple times) recordContainer.innerHTML = ""; // Loop through the array and append each name savedNames.forEach(name => { // Using vanilla JS: recordContainer.innerHTML += `<div>${name}</div>`; // If you prefer jQuery: // $("#record").append(`<div>${name}</div>`); });
Why This Works
- localStorage only supports string values, so we use
JSON.stringify()to turn our array into a storable string, andJSON.parse()to convert it back to an array when we need to read it. - By keeping all names in a single array under one key (
searchNames), we avoid overwriting old entries and can easily add new ones whenever you search.
Bonus: Allow Duplicates (If You Want)
If you don't mind saving the same name multiple times, just remove the includes() check—simply push the new name directly to the savedNames array before saving it back to localStorage.
内容的提问来源于stack exchange,提问作者Dan

