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

JavaScript使用localStorage存储笔记实现页面刷新后数据不丢失问题

实现笔记本地持久化的解决方案

核心实现思路:将所有笔记存在JS数组中,每次新增笔记时同步把数组序列化后存入localStorage,页面加载时读取localStorage的内容反序列化为数组,再渲染到页面上即可实现刷新不丢失数据的效果。


localStorage核心操作说明

localStorage是浏览器提供的本地持久化存储能力,只要用户不手动清理浏览器缓存,存储的数据会永久保留,常用操作如下:

  • localStorage.setItem(键名, 字符串值):向本地存储写入数据
  • localStorage.getItem(键名):根据键名读取本地存储的内容,无对应数据时返回null
  • 因为localStorage仅支持存储字符串类型数据,所以数组/对象类型数据需要用JSON.stringify()转为字符串后再存储,读取时用JSON.parse()转回JS可用的数组/对象格式。

修改后的完整JS代码

//// 变量声明 ////
const noteBtn = document.querySelector('.add-note-btn');
const writeNote = document.querySelector('.note-input');
const allSavedNotes = document.querySelector('.added-notes');
// 自定义存储键名,避免和其他站点存储冲突
const STORAGE_KEY = 'personal_note_list';

// 初始化:读取本地存储的笔记数据,无数据时返回空数组
let notes = JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];

// 统一渲染笔记的公共函数
function renderNotes() {
  // 先清空容器,避免重复渲染
  allSavedNotes.innerHTML = '';
  // 遍历所有笔记生成DOM元素
  notes.forEach(noteText => {
    let newNote = document.createElement('p');
    newNote.className = 'saved-note';
    newNote.textContent = noteText;
    allSavedNotes.appendChild(newNote);
  })
}

// 页面加载完成后先渲染已存储的笔记
renderNotes();

//// 新增笔记逻辑 ////
noteBtn.addEventListener('click', function(e){
  e.preventDefault();
  // 去除输入内容前后空格,过滤空笔记提交
  const inputVal = writeNote.value.trim();
  if (!inputVal) return;

  // 新增笔记到数组
  notes.push(inputVal);
  // 同步更新到localStorage
  localStorage.setItem(STORAGE_KEY, JSON.stringify(notes));
  // 重新渲染页面
  renderNotes();
  // 清空输入框,方便下次输入
  writeNote.value = '';
})

后续扩展提示

如果后续需要实现删除、修改笔记的功能,只需要在操作时先更新notes数组,再调用localStorage.setItem(STORAGE_KEY, JSON.stringify(notes))同步存储,最后调用renderNotes()刷新页面渲染即可,逻辑完全复用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:09:03