You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现多次存储搜索名称至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.

How to Store and Display Multiple Search Names in localStorage

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, and JSON.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:40:17