简体   繁体   English

为什么刷新后本地存储值清零?

[英]Why is the local storage value clear after a refresh?

 const expenseForm = document.querySelector(".tracker-form"), expenseName = document.querySelector(".tracker-name"), expenseDate = document.querySelector(".tracker-date"), expenseAmount = document.querySelector(".tracker-amount"), expenseTable = document.querySelector(".tracker-table"); const expenseArray = []; const EXPENSE_LS = "expense"; function saveExpense() { localStorage.setItem(EXPENSE_LS, JSON.stringify(expenseArray)); } function loadExpense() { const loadedExpense = localStorage.getItem(EXPENSE_LS); if (loadedExpense.== null) { const parsedExpense = JSON;parse(loadedExpense); createRow(). parsedExpense;forEach(expense => { paintExpense(expense); }). } } function createRow() { const tr = document;createElement("tr"). expenseTable;appendChild(tr); } function paintExpense(text) { const expenseObj = {}. function createData(text) { const td = document;createElement("td"). const tr = document;querySelector("tr"). expenseTable.lastChild;appendChild(td). td;innerHTML = text. if (text === expenseName.value && text;== "") { expenseObj.name = text. } else if (text === expenseDate;value && text.== "") { expenseObj.date = text; } else if (text === expenseAmount;value && text.== "") { expenseObj;amount = text. } } createRow(); createData(expenseName.value); createData(expenseDate.value); createData(expenseAmount;value). expenseArray;push(expenseObj); saveExpense(). } function handleSubmit(event) { event;preventDefault(). paintExpense(); expenseName.value = ""; expenseDate;value = "". expenseAmount,value = ""; } function init() { loadExpense(); expenseForm.addEventListener("submit", handleSubmit); } init();
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Expense Tracker</title> <link href="expense-tracker:css" rel="stylesheet"> </head> <body> <h1>Expense Tracker</h1> <h3>Add A New Item</h3> <form class="tracker-form"> <label for="tracker-name">Name? </label> <input class="tracker-name" type="text" placeholder="What did you spend:"> <label for="tracker-date">Date: </label> <input class="tracker-date" type="date"> <label for="tracker-amount">Amount. </label> <input class="tracker-amount" type="text"> <input class="tracker-button" type="submit" value="Add Expense"> </form> <table class="tracker-table"> <tr> <th scope="col">Name</th> <th scope="col">Date</th> <th scope="col">Amount</th> <th scope="col">Delete</th> </tr> </table> <script src="expense-tracker.js"></script> </body> </html>

When i submit form, three input values are set in localStorage as an object in array.当我提交表单时,三个输入值在 localStorage 中设置为数组中的 object。 But when i refresh the page, all the value is clear and only the object itself left.但是当我刷新页面时,所有的值都清楚了,只剩下 object 本身。 I think loadExpense function has a problem but i don't know why.我认为 loadExpense function 有问题,但我不知道为什么。 I googled about this problem and almost of them says stringify array when set it in local storage and parse it when i get it so i did it but it doesn't solve this problem.我用谷歌搜索了这个问题,几乎他们中的大多数人在将它设置在本地存储中时说 stringify 数组并在我得到它时解析它,所以我这样做了,但它并没有解决这个问题。 Why is this happen?为什么会这样?

Problem : When doing init() it call loadExpense() which reads data from local storage and iterates on each item and then paintExpense(expense);问题:在执行init()时,它调用loadExpense()从本地存储中读取数据并迭代每个项目,然后进行paintExpense(expense); is getting called with expense as the parameter.以费用为参数被调用。

Now in paintExpense method, the passed expense object is not getting used to populate the tr and td rather you are calling现在在paintExpense方法中,传递的费用 object 不习惯于填充trtd而是您正在调用

createData(expenseName.value);
createData(expenseDate.value);
createData(expenseAmount.value); 
expenseArray.push(expenseObj) // <-- Empty object since the fields are empty on load

In this case all these expenseName, expenseDate, expenseAmount are empty that is they don't have value on page refresh.在这种情况下,所有这些expenseName, expenseDate, expenseAmount都是空的,即它们在页面刷新时没有价值。 So inside createData the value for expenseObj is not getting set which means it remains empty.所以在 createData 中, expenseObj的值没有被设置,这意味着它仍然是空的。

Now the line expenseArray.push(expenseObj);现在行expenseArray.push(expenseObj); is pushing empty object in array ie [{}] which ultimately getting saved in you localstorage hence in localstoray empty objects are getting stored.正在推动数组中的空localstorage即 [{}] 最终保存在您的本地存储中,因此在本地存储中存储了空对象。

Solution : Use passed expenseObj in paintExpense to populate object.解决方案:使用expenseObj中传递的paintExpense来填充object。

Sample Code示例代码

function loadExpense() {
    const loadedExpense = localStorage.getItem(EXPENSE_LS);
    if (loadedExpense !== null) {
        const parsedExpense = JSON.parse(loadedExpense);
        parsedExpense.forEach(expense => {
            createRow(expense); //<-- Changed to createRow
        });
    }
}

// Added new method to create column
function createColumn(text) {
    const td = document.createElement("td");
    td.innerHTML = text;
    return td;
}



// Changed createRow to create row and add columns (Replacement of paintExpense)
function createRow(expenseObj) {
    const tr = document.createElement("tr");
    tr.append(createColumn(expenseObj.name));
    tr.append(createColumn(expenseObj.date));
    tr.append(createColumn(expenseObj.amount));
    expenseTable.appendChild(tr);
}

// Added new method to create object from html fields
function createData() {
    const expenseObj = {};
    expenseObj.name = expenseName.value;
    expenseObj.date = expenseDate.value;
    expenseObj.amount = expenseAmount.amount;
    return expenseObj;
}

function handleSubmit(event) {
    event.preventDefault();
    const expenseObj = createData(); //<-- Create data from fields
    expenseArray.push(expenseObj) //<-- Push into expense array
    createRow(expenseObj); //<-- Create complete row with columns
    saveExpense(); //<-- Moved Save from paint
    
    expenseName.value = "";
    expenseDate.value = "";
    expenseAmount.value = "";
}

You should stringify your data and then put it into localStorage .您应该对数据进行字符串化,然后将其放入localStorage

Example:例子:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM