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

JavaScript笔记应用固定笔记创建时间 解决旧笔记时间随新增更新问题

问题原因

你存储笔记时已经正确给每条新笔记附加了创建时间,但渲染逻辑存在两个核心错误,才会导致所有笔记时间同步刷新:

  • Array.forEach的回调参数定义错误:forEach回调默认只有三个参数,按顺序是「当前遍历的元素、当前索引、遍历的原数组」,你写的多余参数没有实际意义,且渲染卡片时间时每次都执行new Date()生成当前最新时间,每次调用showNotes(新增笔记、页面刷新都会触发)就会给所有卡片重新赋值当下的时间,历史笔记预先存储的时间根本没被读取使用。
  • 你已经把存储结构从纯字符串改成了{text: 笔记内容, date: 创建时间}的对象格式,但渲染笔记正文时直接输出整个element对象,会显示[object Object],无法正常展示笔记内容。
修复方案

只需要修改showNotes函数的渲染逻辑即可,新增笔记的存储逻辑本身没有问题:

  • 移除forEach里多余的无效参数
  • 渲染笔记正文时读取对象的text字段,同时兼容之前存储的纯文本格式旧笔记
  • 渲染时间时直接读取每条笔记预先存储的date字段做格式化,不要在渲染阶段生成新的时间对象
修正后完整代码
// 从localStorage读取并展示笔记
function showNotes() {
  let notes = localStorage.getItem("notes");
  let notesObj = [];
  if (notes != null) {
    notesObj = JSON.parse(notes);
  }

  let html = "";
  notesObj.forEach(function (element, index) {
    // 兼容旧版本纯文本笔记,统一取到笔记内容
    const noteText = typeof element === 'string' ? element : element.text;
    // 读取预先存储的笔记创建时间格式化,不生成新时间
    const noteTime = new Date(element.date).toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit"
    });
    html += `
            <div class="noteCard card text-center mr-3 mb-3 border-dark" style="width: 344px;">
                    <div class="card-header bg-dark text-light">
                        Featured
                    </div>
                    <div class="card-body">
                        <h5 class="card-title">Note ${index + 1}</h5>
                        <p class="card-text"> ${noteText}</p>
                        <button id="${index}" onclick="deleteNote(this.id)" class="btn btn-outline-danger my-4">Delete Note</button>
                    </div>
                    <div class="card-footer text-light bg-secondary">
                        ${noteTime}
                    </div>
                </div>`;
  });
  let notesElm = document.getElementById("notes");
  if (notesObj.length != 0) {
    notesElm.innerHTML = html;
  } else {
    notesElm.innerHTML = `
            <div class="card text-light bg-dark mb-3" style="width: 1130px;">
        <div class="card-header text-dark bg-warning"><b>Message For You!</b></div>
        <div class="card-body">
            <p class="card-text"><h3>Nothing to show! Use "Add a Note" section above to add notes.</h3> </p>
        </div>
        </div>`;
  }
}

// 新增笔记存入localStorage逻辑
let addBtn = document.getElementById('addBtn');
addBtn.addEventListener('click', function (e) {
    let addTxt = document.getElementById("addTxt");
    if (addTxt.textLength == 0) {
        alert("Please write something in text box first!")
    }
    else {
        let notes = localStorage.getItem("notes");
        let notesObj = [];
        if (notes != null) {
            notesObj = JSON.parse(notes);
        }
        notesObj.push({text: addTxt.value, date : new Date()});
        localStorage.setItem("notes", JSON.stringify(notesObj));
        addTxt.value = "";
        showNotes();
    }
})

注:代码里给notesObj补了局部变量声明,避免隐式创建全局变量带来的额外问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 05:15:41