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

为何数据已存入Local Storage但无法在页面显示?

问题修复方案

你的代码存在几个关键问题,导致内容存入Local Storage后无法在页面显示,逐个修正如下:

1. LocalStorage 键值存储逻辑颠倒

你当前把输入内容作为键、父元素标识作为值存入LocalStorage,但读取时用item1作为键获取,逻辑完全相反。正确逻辑应该是把输入框的唯一ID作为键,输入内容作为值存储。

2. 获取元素标识的方法错误

$(this).parent('id')是错误写法,要获取对应输入框的ID,应该用$(this).siblings('.description').attr('id');若要获取父元素ID则用$(this).parent().attr('id')。

3. 读取内容时的选择器错误

$('#item1.description')是错误的选择器语法,ID选择器优先级最高,直接写$('#item1')即可定位到目标输入框。

修正后的完整代码

JavaScript 代码

$('.saveBtn').on('click', function() {
  // 获取输入框的内容
  var inputValue = $(this).siblings('.description').val();
  // 获取对应输入框的ID作为存储键
  var itemId = $(this).siblings('.description').attr('id');

  // 以ID为键、输入内容为值存入LocalStorage
  localStorage.setItem(itemId, inputValue);
});

// 页面加载时读取对应ID的内容并填充到输入框
$('#item1').val(localStorage.getItem('item1'));

HTML 代码

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row time-block">
  <div class="col-md-1 hour">9am</div>
  <textarea class="col-md-10 description" id="item1"> </textarea>
  <button class="saveBtn col-md-1"><i class="fa fa-save"></i></button>
</div>

批量处理优化建议

如果页面有多个时间块,可通过循环批量读取LocalStorage内容,避免重复编写代码:

// 遍历所有输入框,根据ID自动填充对应存储内容
$('.description').each(function() {
  var itemId = $(this).attr('id');
  $(this).val(localStorage.getItem(itemId));
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 12:27:16