我正在尝试将当前时间和日期存储在一个表中。当前,在页面加载时,我的代码会更改日期以反射(reflect)当前时间。
我的代码如下所示:
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>');
});
FIDDLE
关于javascript - 如何将多个前置日期存储到localStorage?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34120975/