【问题标题】:How do I store multiple prepended dates to localStorage?如何将多个前置日期存储到 localStorage?
【发布时间】:2015-12-07 03:05:19
【问题描述】:

我正在尝试将当前时间和日期存储在表格中。目前,在页面加载时,我的代码会更改日期以反映当前时间。

我的代码如下所示:

function currentDate() {
  var d = new Date();
  return d.toString();
}
window.onload = function() {
   localStorage.setItem("date", currentDate());
   $('#current-location').prepend('<tr<td>'+localStorage.getItem("date")+'</td>');
}

我试过console.log(localStorage),所以我知道那里保存了一个日期。但是,我想存储重新加载页面的日期(比如第二次加载页面并出现 2 个日期等)我需要一个数组吗?如果是这样,我将如何将数组内容添加到表中?

【问题讨论】:

  • 每次加载页面时,js 变量都会被重置。您需要将其存储在会话变量或 cookie 中。加载页面时,将日期添加到 cookie。显示时从 cookie 中获取它。

标签: javascript jquery html local-storage onload


【解决方案1】:

是的,您可以为此使用数组,然后继续将日期推送到数组中,就像这样

function currentDate() {
  var d = new Date();
  return d.toString();
}

var arr = JSON.parse(localStorage.getItem("date") || "[]");

arr.push(currentDate())

localStorage.setItem("date", JSON.stringify(arr));

arr.forEach(function(item) {
  $('#current-location').prepend('<tr><td>' + item + '</td></tr>');
});

FIDDLE

【讨论】:

  • 感谢您的解决方案。唯一的问题是它从“Sunday”中的“S”抛出错误“Uncaught SyntaxError: Unexpected token S”。
  • 真的吗?小提琴不适合你?它对我来说很好,我不确定日期中的字符串如何在给定的代码中引发该错误?
  • 哦,等等,您可能没有清除您的 localStorage 是吗?尝试将密钥从 "date" 更改为其他内容。
  • 哦,是的。谢谢!我还不知道所有的技巧。 :)
【解决方案2】:

因此,我将添加一个对象作为 JSON,并将其字符串化版本保存到 localStorage。作为概念证明,您可以使用以下内容:

1) 初始化localStorage中的对象:

var listOfDates = {
  dates: []
};
localStorage.setItem('myDates', JSON.stringify(listOfDates));

根据您的需要,您可能希望将其放在“if(!localStorage.getItem('myDates'))”中

2) 创建一个函数,读取存储,解析 JSON,向 dates 数组添加一项,然后保存回 localStorage:

addDateRowToTable = function() {

  var listOfDates = JSON.parse(localStorage.getItem('myDates'));
  listOfDates.dates.push(currentDate());
  localStorage.setItem('myDates', JSON.stringify(listOfDates));

  for(var i=0; i< listOfDates.dates.length; i++) {
   // do whatever you need to
  }
}

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2022-08-17
    • 2017-10-26
    • 2011-02-19
    相关资源
    最近更新 更多