![](/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.