我一直在做一个项目,允许用户提交关于他们去过的地方的记忆,并跟踪提交记忆时的位置。我唯一的问题是尝试将 localStorage 与应用程序一起使用,我阅读了有关 JSON.stringify 和 JSON.parse 的信息,但还不明白如何在我的代码中使用它们。
这是我的 form.js 它处理表单并抓取文本字段。单击添加按钮(在显示详细信息页面上)或输入详细信息按钮时,它会清除表单。最后它接收到信息并将消息发送回窗口。
function processForm(){
var locate = document.myform.locate.value;
var details = document.myform.details.value;
var storeData = [];
localStorage.setItem("locate", JSON.stringify(locate));
localStorage.setItem("details", JSON.stringify(details));
alert("Saved: " + localStorage.getItem("locate") + ", and " + localStorage.getItem("details"));
var date = new Date,
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
ampm = hour > 12 ? "PM" : "AM";
hour = hour % 12;
hour = hour ? hour : 12; // zero = 12
minute = minute > 9 ? minute : "0" + minute;
hour = hour > 9 ? hour : "0" + hour;
date = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + ampm;
localStorage.setItem("date", JSON.stringify(date));
storeData.push(locate, details, date);
localStorage.setItem("storeData", JSON.stringify(storeData));
}
function clearForm(){
$('#myform').get(0).reset();
}
function retrieveFormInfo(){
var data = JSON.parse(localStorage.getItem("storeData"));
var locate = JSON.parse(localStorage.getItem("locate"));
$("#locate2").html("Place: " + locate);
var details = JSON.parse(localStorage.getItem("details"));
$("#details2").html("Description: " + details);
var date = JSON.parse(localStorage.getItem("date"));
$("#date").html(date);
}
但我遇到的主要问题是我确实知道如何使用 JSON.stringify 和 JSON.parse 正确获取该信息并将其动态地附加到带有 html 元素的窗口,主要就像一个记忆列表。
任何帮助表示赞赏!
原文由 king_sw4 发布,翻译遵循 CC BY-SA 4.0 许可协议
香草JS:
查询: