我一直致力于一个项目,允许用户提交他们访问过的地方的记忆,并跟踪记忆提交的位置.我唯一的问题是尝试将localStorage与app一起使用,我读到了
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元素的窗口,主要就像一个记忆列表.
任何帮助表示赞赏!
解决方法
Vanilla JS
var printStorageBody = function () { var body = document.querySelector("body"); var pre = document.createElement("pre"); body.innerHTML = ""; pre.innerText = JSON.stringify(localStorage,null,'\t'); body.appendChild(pre); }
jQuery
var printStorageBody = function () { $("body").html(""); $("<pre>") .text(JSON.stringify(localStorage,'\t')) .appendTo("body"); }