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

基于动态创建textarea的本地存储设置问题求助

解决方案

核心问题是你共用了同一个localStorage键,导致所有笔记都被最后保存的内容覆盖。要解决这个问题,我们让每个时段的笔记对应独立的存储键,直接用textarea的ID作为唯一标识即可。

1. 修改保存逻辑

点击保存按钮时,获取对应textarea的ID,用这个ID作为localStorage的键来存储内容:

$('.saveBtn').on('click', function () {
  // 找到当前按钮对应的textarea
  const targetTextarea = $(this).prev('.description');
  // 获取textarea的ID作为存储键
  const noteKey = targetTextarea.attr('id');
  // 获取输入的笔记内容
  const noteContent = targetTextarea.val();
  // 存入localStorage
  localStorage.setItem(noteKey, noteContent);
});

2. 修改页面加载时的恢复逻辑

遍历所有textarea,根据各自的ID从localStorage中读取对应的值,再填充到对应的输入框:

// 页面加载完成后恢复所有时段的笔记
$(function() {
  $('.description').each(function() {
    const noteKey = $(this).attr('id');
    const savedNote = localStorage.getItem(noteKey);
    if (savedNote !== null) {
      $(this).val(savedNote);
    }
  });
});

额外提示:动态元素的事件绑定

如果你的按钮是在绑定点击事件之后才动态创建的,上面的点击事件可能不会生效,这时候需要用事件委托来绑定:

// 事件委托,确保动态创建的按钮也能触发保存
$(document).on('click', '.saveBtn', function () {
  const targetTextarea = $(this).prev('.description');
  const noteKey = targetTextarea.attr('id');
  const noteContent = targetTextarea.val();
  localStorage.setItem(noteKey, noteContent);
});

这样每个时段的笔记都会存在独立的localStorage项里(比如note-9、note-10),刷新页面时也只会把对应的值填充到对应的textarea中,不会出现所有框都显示同一内容的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:42:45