首页 > 解决方案 > 我想使用 localStorage 来保存用户输入的一些数据,以便我可以在 HTML 中显示信息

问题描述

所以我正在为一些实践构建一个餐厅点餐系统,用户选择一个服务员并向所选服务员添加订单或评论。

然后使用创建的方法将其推送到 Waiter 对象。

我想存储用户推算的数据,以便在页面重新加载后可以在控制台中查看。

我想使用 JSON 而不是 PHP/其他来实现这一点。

因此,当我重新打开页面时,任何推送到数组的数据在登录到控制台时仍然可见。

任何链接或代码将不胜感激

/*

//Waiters Section

*/


//Waiter Constructor
class Waiter {
    constructor(name) {
        this.name = name;
        this.order = [];
        this.total = 0;
        this.comment = [];
    }


    //Methods to map() the price argument
    //and then reduce() to get the total  
    addFood(item) {
        this.order.push(item);
        this.total = this.order
            .map(o => o.price, 0)
            .reduce((a, b) => a + b, 0);
    };


    //Method to push any comments to the selected waiter
    addComment(c){
        this.comment.push(c) + " ";      
    }


};





//Array to store waiters
const waiters = [
    new Waiter('Timo'),
    new Waiter('Lucian'),
    new Waiter('Arpi')

];





//Adding the waiters to the options menu
const waitersEl = document.getElementById('waiters');
waiters.forEach(({
    name
}) => waitersEl.options.add(new Option(name)));





/*

//Food Section Main

*/

//Food Constructor
class Item {
    constructor(item, price) {
        this.item = item;
        this.price = price;
        this.label = `${item} (${price})`;
    }
}



//Main food array
const mainFood = [
    new Item('Peene Primvera', 14),
    new Item("Lasagne", 14),
    new Item("Fillet Steak", 20)
];






//Addin the options for each food and price item inside the dropdown menu
const foodMain = document.getElementById('menuMain');
mainFood.forEach(({
    label,
    item
}, index) => foodMain.options.add(new Option(label, index)));




/*

//Fucntion for when the form is submited it adds the  

*/
const formEl = document.getElementById('mainForm');

formEl.onsubmit = function (e) {

    //Selecting the comment input on the form to pass to the 
    //comment waiters array.
    const comment = document.getElementById('comment').value;


    //Selecting the choosen index from the user food and which waiter orderd //it which waiter.
    //Selects the choosen food to pass to the addFood method in the waiter //class.
    const foodItemIndex = foodMain.options[foodMain.selectedIndex].value;
    const foodItem = mainFood[foodItemIndex];


    //Selecting the waiter to push valid informaiton to.
    const waiterName = waitersEl.options[waitersEl.selectedIndex].value;
    const waiter = waiters.find(({name}) => name === waiterName);


    //Logic to check when submited if both feilds are true proceed.
    //The statements check to see which feild values have been entered
    //Then it call's the corresponding method from the waiter class and
    //pushes the value to the choosen array
    if (waiter && foodItem && comment) {
        waiter.addFood(foodItem)
        waiter.addComment(comment);
        console.log(waiters);
    }
    else if (waiter && comment) {
        waiter.addComment(comment);
        console.log(waiters);        
    }
    else if (waiter && foodItem){    
        waiter.addFood(foodItem)
        console.log(waiters);
    }




    formEl.reset();  
    return false; // prevents redirect/refresh

};

表单提交一次后:

0: Waiter
comment: ["This form has been submitted I will now close the window and when I reopen I will not be here"]
name: "Timo"
order: [Item]
total: 14

现在当我重新打开时:

0: Waiter
comment: []
name: "Timo"
order: []
total: 0

我想要它,所以当我重新打开数据时,数据仍在数组中。

标签: javascripthtmljson

解决方案


提交表单后,您使用 localStorage.setItem(key,value); 写入 localStorage;

表单的 OnSubmit:将每个 WaiterObject 推送到一个 items 数组,然后将 items 数组保存到 localStorage

使用 localStorage.getItem() 方法从 localStorage 检索值并设置为项目并显示项目,

这是上面解释的存储和检索逻辑的示例

https://coderwall.com/p/ewxn9g/storing-and-retrieving-objects-with-localstorage-html5

推荐阅读