[英]How do I store multiple prepended dates to localStorage?
我試圖將當前時間和日期存儲在表格中。 目前,在頁面加載時,我的代碼會更改日期以反映當前時間。
我的代碼看起來像這樣:
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個日期等)我需要一個數組嗎? 如果是這樣,我如何將數組內容添加到表中?
是的,您可以使用一個數組,並繼續將日期推送到數組,就像這樣
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>');
});
因此,我將一個對象添加為JSON並將其字符串化版本保存到localStorage中。 作為概念證明,您可以使用以下內容:
1)在localStorage中初始化對象:
var listOfDates = {
dates: []
};
localStorage.setItem('myDates', JSON.stringify(listOfDates));
根據您的需要,您可能希望將其放在“if(!localStorage.getItem('myDates'))”中
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
}
}
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.