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

使用jQuery无法正确读取和展示localStorage中的数据

问题解决:读取并展示localStorage中的日程任务

核心问题分析

当前代码的问题在于页面加载时没有从localStorage读取已保存的任务并填充到对应文本框,另外你尝试使用JSON.parse时可能因存储格式不匹配或错误处理导致代码中断,进而让timeBlock行无法生成。


方案一:适配现有单个键值对存储逻辑

直接在创建每个textInput后,读取对应小时的存储值填充进去,无需修改保存逻辑:

// DOM elements pulling from HTML
var currentDay = $("#currentDay");
var schedule = $('.container');

// Moment.js variables
var now = moment().format("dddd, MMMM Do YYYY");
var currentHour = moment().hour();

// Global variables
var workDay = 9;

// Setting Current Day to top of the calendar
$(currentDay.text(now));
  
// Adding Rows dynamically using the DOM
for (var i = 0; i < workDay; i++) {

  // Setting time blocks main divs
  var timeBlock = $("<div>").addClass("row time-row");
  timeBlock.attr("id", i + 1);

  // Setting hour column
  var hourCol = $("<div>").addClass("hour col-1");
  hourCol.text(moment().hour(i + workDay).format("hA"));

  // Setting save column
  var saveCol = $("<button>").addClass("saveBtn col-1 fas fa-save");
  saveCol.attr("data-index", i);

  // Setting text input area for timeblocks
  var textInput = $("<textarea>").addClass("task time-block future");

  // --------------------------新增代码--------------------------
  // 读取当前小时对应的已保存任务,填充到文本框
  var savedTask = localStorage.getItem(i + 1);
  if (savedTask) {
    textInput.val(savedTask);
  }
  // -----------------------------------------------------------

  /* Appending all columns to timeBlock divs and then
  appending timeBlock div to main Schedule container */
  timeBlock.append(hourCol);
  timeBlock.append(textInput);
  timeBlock.append(saveCol);
  schedule.append(timeBlock);

  // Setting textArea color depending on time as defined by currentHour variable
  if (currentHour === (i + workDay)) {
    textInput.attr("class", "task col-10 present");
  }
  else if (currentHour > (i + workDay)){
    textInput.attr("class", "task col-10 past");
  };
};

// Saving work schedule tasks to localStorage()
$('.saveBtn').on("click", function(event) {
  event.preventDefault();
  var workHour = $(this).parent().attr("id");
  var setTask = $(this).siblings(".task").val();
  localStorage.setItem(workHour, setTask);
});

方案二:改用数组存储更易维护(推荐)

用数组统一存储所有任务,匹配你提到的JSON.parse(localStorage.getItem(storedName)) || []用法,避免单个键值对的零散存储:

// DOM elements pulling from HTML
var currentDay = $("#currentDay");
var schedule = $('.container');

// Moment.js variables
var now = moment().format("dddd, MMMM Do YYYY");
var currentHour = moment().hour();

// Global variables
var workDay = 9;
// 初始化任务数组:读取存储的数组,若无则创建空数组(长度匹配workDay)
var tasks = JSON.parse(localStorage.getItem('scheduleTasks')) || Array(workDay).fill('');

// Setting Current Day to top of the calendar
$(currentDay.text(now));
  
// Adding Rows dynamically using the DOM
for (var i = 0; i < workDay; i++) {

  // Setting time blocks main divs
  var timeBlock = $("<div>").addClass("row time-row");
  timeBlock.attr("id", i + 1);

  // Setting hour column
  var hourCol = $("<div>").addClass("hour col-1");
  hourCol.text(moment().hour(i + workDay).format("hA"));

  // Setting save column
  var saveCol = $("<button>").addClass("saveBtn col-1 fas fa-save");
  saveCol.attr("data-index", i);

  // Setting text input area for timeblocks
  var textInput = $("<textarea>").addClass("task time-block future");
  // 填充已保存的任务
  textInput.val(tasks[i]);

  /* Appending all columns to timeBlock divs and then
  appending timeBlock div to main Schedule container */
  timeBlock.append(hourCol);
  timeBlock.append(textInput);
  timeBlock.append(saveCol);
  schedule.append(timeBlock);

  // Setting textArea color depending on time as defined by currentHour variable
  if (currentHour === (i + workDay)) {
    textInput.attr("class", "task col-10 present");
  }
  else if (currentHour > (i + workDay)){
    textInput.attr("class", "task col-10 past");
  };
};

// Saving work schedule tasks to localStorage()
$('.saveBtn').on("click", function(event) {
  event.preventDefault();
  var index = $(this).data('index'); // 用data-index获取任务在数组中的位置
  tasks[index] = $(this).siblings(".task").val();
  localStorage.setItem('scheduleTasks', JSON.stringify(tasks)); // 数组转JSON字符串存储
});

为什么之前行消失?

你尝试使用JSON.parse时,若直接对单个字符串任务使用JSON.parse(localStorage.getItem(...)),当存储值不存在时getItem返回null,JSON.parse(null)会抛出错误,导致循环代码中断,后续的timeBlock无法生成,所以页面上所有行消失。方案二中我们用|| Array(workDay).fill('')处理了存储为空的情况,确保数组始终有效,循环正常执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 09:35:22