我需要从本地存储加载一个数组。
我将表单输入添加到本地存储的数组中,如下所示:
document.querySelector("#addMeal").addEventListener("click", newMeal);
function newMeal(e){
e.preventDefault();
let title = document.querySelector("#title").value;
let img = document.querySelector("#img").value;
let book = document.querySelector("#book").value;
let calories = document.querySelector("#calories").value;
let servings = document.querySelector("#servings").value;
let type = document.querySelector("#type").value;
let price = document.querySelector("#price").value;
let cook = document.querySelector("#cook").value;
let quantity = document.querySelector("#quantity").value;
let newMeal={
id: 23,
title: title,
img: img,
book: book,
calories: calories,
servings: servings,
type: type,
price: price,
cook: cook,
quantity: quantity};
meals.push(newMeal);
console.log(meals);
// Put the object into storage
localStorage.setItem('meals', JSON.stringify(meals));}
现在我需要将该数组加载到另一个页面中。 我已经有了这部分代码,但这不起作用。 有谁知道我做错了什么?
document.addEventListener('DOMContentLoaded', loadMeals);
function loadMeals() {
let retrievedObject = localStorage.getItem('meals');
console.log(meals);
let i = 0;
let id = 1;
let fillMealList = document.querySelector("#fillMealList");
for (let i = 0; i < meals.length; i++) {
let item = meals.find(item => item.id === id);
fillMealList.innerHTML +=
"<article class='objectP'>"+
"<h3>" + item.title + "</h3>"+
"<figure>"+
"<img src='images/" + item.img + "'" +">" +
"<figcaption>"+
"Meal by: " +"<span>" + item.cook + "</span>" +
"</figcaption>" +
"</figure>"+
"<div class='info'>"+
"<p>€ <span>" + item.price + "</span>" + "/pp" + "</p>" +
"<a href='javascript:addToCart(" + item.id + ")' class='addToCart'>Order</a>"+
"</div>"+
"</article>";
id++;
}}
最佳答案
据我所知,你有 4 个错误。
首先,您需要解析从本地存储收到的字符串。
let retrievedObject = JSON.parse(localStorage.getItem('meals'));
其次,console.log(meals);
可能会抛出错误,因为我在该范围内看不到meals
。
第三,将食物放入 localStorage 的行有一个错误的分号。它会抛出一个错误。尝试将分号放在行尾。
localStorage.setItem('meals', JSON.stringify(meals));
第四个可能是您遇到的与第二个问题类似的主要问题。如果meals
没有定义为数组,则不能使用它的原型(prototype)方法push
,它会抛出错误。添加常量膳食 = []
。
关于javascript - JS : Load localstorage in other page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53850741/