简体   繁体   English

如何将多个前置日期存储到localStorage?

[英]How do I store multiple prepended dates to localStorage?

I am trying to store the current time and date in a table. 我试图将当前时间和日期存储在表格中。 Currently, on a page load, my code changes the date to reflect the current time. 目前,在页面加载时,我的代码会更改日期以反映当前时间。

My code looks like this: 我的代码看起来像这样:

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>');
}

I tried console.log(localStorage) , so I know that one date is being saved there. 我试过console.log(localStorage) ,所以我知道那里有一个日期。 However, I want to store the date when the page is reloaded (like load the page a second time and 2 dates appear, etc) Do I need an array for this? 但是,我想存储重新加载页面的日期(如第二次加载页面和出现2个日期等)我需要一个数组吗? If so, how would I add array contents to a table? 如果是这样,我如何将数组内容添加到表中?

Yes, you could use an array for that, and just keep pushing dates to the array, like this 是的,您可以使用一个数组,并继续将日期推送到数组,就像这样

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 小提琴

So, I'd add an object as a JSON and save it's stringified version into localStorage. 因此,我将一个对象添加为JSON并将其字符串化版本保存到localStorage中。 As a proof of concept you can use something like this: 作为概念证明,您可以使用以下内容:

1) Initialize the object in localStorage: 1)在localStorage中初始化对象:

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

Depending of your needs, you might want to put this in an "if(!localStorage.getItem('myDates'))" 根据您的需要,您可能希望将其放在“if(!localStorage.getItem('myDates'))”中

2) Make a function that reads the storage, parses the JSON, adds an item to the dates array, and saves back to localStorage: 2)创建一个读取存储的函数,解析JSON,将项添加到日期数组,然后保存回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
  }
}

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM