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