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

使用Local Storage存储城市搜索记录时innerHTML覆盖内容的实现问题问询

实现方案

你遇到的两个核心问题及修正思路如下:

  1. 本地存储仅支持存字符串,你当前是单个存储城市,没有维护历史搜索的数组结构,无法支撑多记录展示
  2. 直接对innerHTML用=赋值会覆盖原有内容,用全量渲染列表的方式更稳妥,不会出现HTML结构错乱

具体实现步骤

  • 存储逻辑修改:每次新增搜索城市时,先读取本地已有的历史记录数组,追加新城市后再转成JSON字符串存回LocalStorage,可自行加去重、限制存储条数的逻辑
  • 渲染逻辑修改:每次需要更新展示时,读取存储的城市数组,遍历生成完整的有序列表结构,再赋值给form元素的innerHTML

修正后代码示例

HTML

<form class="recent-search" id="demo"></form>

JavaScript

// 新增搜索城市时调用该方法存储
function saveSearchCity(cityName) {
  // 读取已有历史记录,无记录则初始化空数组
  const historyList = JSON.parse(localStorage.getItem('recentSearchCities') || '[]')
  // 可选:城市名转小写去重,避免重复存储
  const formatName = cityName.toLowerCase()
  if (!historyList.includes(formatName)) {
    historyList.push(formatName)
    // 可选:限制最多存储10条历史记录,超出则删除最早的一条
    if (historyList.length > 10) {
      historyList.shift()
    }
    // 转JSON字符串存入LocalStorage
    localStorage.setItem('recentSearchCities', JSON.stringify(historyList))
  }
  // 存储完成后触发重新渲染
  renderHistoryList()
}

// 渲染历史搜索列表
function renderHistoryList() {
  const historyList = JSON.parse(localStorage.getItem('recentSearchCities') || '[]')
  // 拼接完整的有序列表HTML
  const listHtml = `<ol>
    ${historyList.map(item => `<li>${item}</li>`).join('')}
  </ol>`
  document.getElementById('demo').innerHTML = listHtml
}

// 页面加载完成后先渲染一次已有历史记录
renderHistoryList()

如果你想用追加内容的方式实现也可以,需要先在form中提前写好<ol>标签,每次新增时选中ol元素,用innerHTML += <li>新城市</li>即可,但这种方式在页面刷新后需要重新渲染已有记录,不如全量渲染的方式逻辑统一。

内容的提问来源于stack exchange,提问作者uglybaldbaby

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:09:03