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

JavaScript切换单元格颜色后 如何实现页面刷新状态不丢失

单元格标记状态持久化实现方案

直接用浏览器原生的localStorage做本地存储即可,数据会永久保存在用户本地浏览器中,刷新页面、重启浏览器都不会丢失,无需后端接口支持,完全匹配你的使用场景。

改造要点

  • 给每个表格单元格绑定唯一位置标识,推荐按「行索引+列索引」生成固定id,确保每个格子的状态能精准对应
  • 每次点击切换单元格颜色时,同步把全量单元格的颜色状态序列化后存入localStorage
  • 页面初始加载时,自动读取localStorage里的历史状态,还原每个单元格的背景色;如果没有历史记录就用默认的绿色初始值

改造后完整代码

<!DOCTYPE HTML>
<html>
<head>
  <title>每周可用时段标记</title>
  <script type="text/javascript">
    // 页面加载完成后还原历史状态
    window.onload = function() {
      const savedState = localStorage.getItem('timeSlotMarks')
      if (savedState) {
        const stateMap = JSON.parse(savedState)
        const cells = document.querySelectorAll('td')
        cells.forEach(cell => {
          const cellId = cell.dataset.cellId
          if (stateMap[cellId]) {
            cell.style.backgroundColor = stateMap[cellId]
          }
        })
      }
    }

    // 切换颜色+同步保存状态
    function ilumina(celda){
      if (celda.style.backgroundColor == "yellow") {
        celda.style.backgroundColor = "green";
      } else {
        celda.style.backgroundColor = "yellow";
      }
      saveAllState()
    }

    // 保存所有单元格状态到localStorage
    function saveAllState() {
      const stateMap = {}
      const cells = document.querySelectorAll('td')
      cells.forEach((cell) => {
        // 给单元格生成唯一位置id
        if (!cell.dataset.cellId) {
          const rowIndex = cell.parentElement.rowIndex
          const colIndex = cell.cellIndex
          cell.dataset.cellId = `r${rowIndex}c${colIndex}`
        }
        stateMap[cell.dataset.cellId] = cell.style.backgroundColor || 'green'
      })
      localStorage.setItem('timeSlotMarks', JSON.stringify(stateMap))
    }
  </script>
</head>
<body>
  <table border="1" width="50%">
    <tr>
      <td bgcolor="green" onclick="ilumina(this)">&nbsp;</td>
      <td bgcolor="green" onclick="ilumina(this)">&nbsp;</td>
      <td bgcolor="green" onclick="ilumina(this)">&nbsp;</td>
      <td bgcolor="green" onclick="ilumina(this)">&nbsp;</td>
    </tr>
  </table>
</body>
</html>

补充说明

  • 存储的key名timeSlotMarks可以根据你的需求自定义,只要不和同域名下其他存储key冲突即可
  • 如果后续需要加清空标记的功能,直接调用localStorage.removeItem('timeSlotMarks')后刷新页面就能回到全绿的初始状态
  • localStorage单域名存储容量上限一般为5MB左右,存储这类单元格颜色状态完全够用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:27:25