![](/img/trans.png)
[英]How can I write JavaScript cookies to keep the data persistent after page reloads on my form?
[英]How can I keep the data of a form in my javascript if the submit button reloads the page
我有一個帶有 2 個文本、1 個數字和 1 個單選輸入的簡單表單,我正在嘗試將這些數據帶入我的 javascript 以創建一個使用構造函數創建的對象數組,但在我點擊提交按鈕和控制台的那一刻記錄它顯示為空的數組,我想是因為重新加載了頁面,但我不確定。
這是我的javascript代碼:
let myLibrary = []; //the array I wantd to fill with the objects const form = document.querySelector('#form'); //the form itself // the constructor function Book (title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; } // the submit listener, which takes the data of the form and sends it as argument of the function that pushes the new object to the array form.addEventListener('submit', (e) => { const data = Object.fromEntries(new FormData(e.target).entries()); addBookToLibrary(data); }); function addBookToLibrary (data) { myLibrary.push(new Book(data.title, data.author, data.pages, data.read)); }
我嘗試將 preventDefault() 方法應用於提交按鈕,但這會停止提交表單。 我也嘗試過使用 FormData() 但我遇到了同樣的問題。
我做了什么:
let myLibrary = []; const data = document.querySelector('#form').elements; // HTMLFormElement.elements const btnSubmit = document.querySelector('#btnSubmit'); // Button type button function Book (title, author, pages, read) { this.title = title; this.author = author; this.pages = pages; this.read = read; } // Take the "value" of each element of the form and create a new Book object function addBookToLibrary (data) { myLibrary.push(new Book(data[0].value, data[1].value, data[2].value, data[3].value)); console.log(myLibrary); } // The listener that calls the function btnSubmit.addEventListener('click', () => { addBookToLibrary(data); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.