无法将表单提交数据保存并显示到 localStorage

问题描述 投票:0回答:1

我正在尝试创建一个基本脚本,从 HTML 表单中获取信息并将其显示在页面上。这个项目只是为了练习我目前通过自学正在学习的JavaScript功能。

现在提交表单会在页面上创建一张卡片,显示提交的信息,并且每次提交表单时都会创建一张新卡片。然而,我现在面临的挑战是,当刷新页面时,所有卡片都消失了。

我正在尝试弄清楚如何使用 localStorage 并在我的代码中添加了一些基本功能;但是我发现刷新页面时卡片仍然消失。我的问题是:

  1. 如何检查表单提交的数据是否确实保存在某处?
  2. 如何编辑代码以在页面刷新时继续显示页面上现有的卡片?

这是我在 CodePen 上的代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flashcard Project</title>
    <link rel="stylesheet" href="./flashcard_styles.css">
</head>
<body>
    <div class="form-wrapper">
        <h1 class="form-title">Add a word</h1>
        <form id="vocab-form" method="POST">
            <div class="input-group">
                <label for="word">Word</label>
                <input id="word" name="word" type="text" placeholder="詞彙">
            </div>
            <div class="input-group">
                <label for="meaning">Meaning</label>
                <input id="meaning" name="meaning" type="text" placeholder="vocabulary">
            </div>
            <div class="input-group">
                <label for="notes">Notes</label>
                <textarea id="notes" name="notes" rows="6" cols="30"></textarea>
            </div>
            <button id="submit" type="submit" value="submit">Add</button>
        </form>
    </div>
    <div class="vocab-grid">
    </div>

    <script src="./flashcard_script.js"></script>
</body>
</html>
const myVocab = [];

function saveData() {
    localStorage.setItem('myVocab', JSON.stringify(myVocab));
}

function loadData() {
    const storedData = localStorage.getItem('myVocab');
    if(storedData) {
        myVocab.push(...JSON.parse(storedData));
    }
}

loadData();

const form = document.querySelector('form');
const vocabGrid = document.querySelector('.vocab-grid');

// define a constructor function to create vocab objects
function Vocab(word, meaning, notes) {
    this.word = word;
    this.meaning = meaning;
    this.notes = notes;
}

// define a function to add new Vocab to myVocab on form submit click
function addVocab(event) {
    event.preventDefault();

    const data = new FormData(event.target);

    let formObj = {}; // initialize empty object to store form values

    // loop thru FormData entried
    for(let [key, value] of data.entries()) {
        formObj[key] = value; // stores the values with their keys within the formObj object
    }

    // convert the stored formObj to a more useful newVocab object, using the constructor function created above
    const newVocab = new Vocab(formObj.word, formObj.meaning, formObj.notes);
    
    myVocab.push(newVocab);

    // clear form after submission
    event.target.reset();

    // save the form submission data to localStorage
    saveData();

    return newVocab;
}

// this function will run every time the submit button is clicked
form.addEventListener('submit', function(event) {

    // first, call the addVocab function, store its result in a new variable
    const addedVocab = addVocab(event);

    // second, create the DOM elements needed to display the vocab on a card
    const newVocabCard = document.createElement('div');
    newVocabCard.classList.add('vocab-card');
    newVocabCard.style.cssText = `
        padding: 10px;
        border: 3px solid black;
        color: var(--drkPurple);
        background-color: white;
        border-radius: 5px;
        box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5);`

    const vocabWord = document.createElement('p');
    vocabWord.innerText = addedVocab.word;

    const vocabMeaning = document.createElement('p');
    vocabMeaning.innerText = addedVocab.meaning;

    const vocabNotes = document.createElement('p');
    vocabNotes.innerText = addedVocab.notes;

    newVocabCard.appendChild(vocabWord);
    newVocabCard.appendChild(vocabMeaning);
    newVocabCard.appendChild(vocabNotes);

    vocabGrid.appendChild(newVocabCard);
});

我是一个完全的 JavaScript 初学者,这是我第一次尝试使用 API,所以解决这个问题的最简单方法对我的学习来说是最好的!预先感谢!

javascript json forms local-storage
1个回答
0
投票

您的数据正在保存到 localStorage - 我使用您的 codepen 上的网络工具进行了验证。问题是您没有代码可以在页面加载时生成卡片。

我建议创建一个接受 vocab 对象的函数,并向 dom 添加相应的卡片(类似于您在提交侦听器中的代码)。

在调用 loadData 的地方,您将循环遍历词汇数组并为数组中的每个项目调用该函数。您还可以在提交处理程序中使用这个新函数来减少代码重复。这有道理吗?

© www.soinside.com 2019 - 2024. All rights reserved.