簡體   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