繁体   English   中英

如果提交按钮重新加载页面,我如何将表单的数据保留在我的 javascript 中

[英]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() 但我遇到了同样的问题。

我做了什么:

  1. 更改了提交按钮并添加了常规按钮类型按钮以防止页面重新加载。
  2. 使用 HTML 表单的“元素”属性获取表单的数据,该属性返回所有表单控件的列表,可以通过索引访问 -> https://developer.mozilla.org/en-US/docs /Web/API/HTMLFormElement/元素
  3. 创建将每个元素的“value”属性作为构造函数的参数传递的对象,并将其推送到数组中
  4. 为按钮创建一个点击监听器,并调用创建对象的函数。

 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.

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