创建新的对象实例并将其推入纯Javascript数组中

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

我正在尝试创建一种表单,该表单在提交时会创建一个具有输入值的新对象,然后将该对象存储在数组中。

由于某种原因,该数组正在“重置”并且没有保存对象。

let myLibrary = []

function Book(title,author,pages,read) {
	this.title = title
	this.author = author
	this.pages = pages
	this.read = read
	myLibrary.push(this)
}


function checkForm(){
	let name = document.querySelector('input[name="title"]').value
	let author = document.querySelector('input[name="author"]').value
	let pages = document.querySelector('input[name="pages"]').value
	let read = document.querySelector('input[name="read"]').checked
  new Book(name,author,pages,read)

}

submit.addEventListener("click",checkForm);
javascript arrays constructor push
3个回答
0
投票

我不确定,因为我试图说明您的代码实际上存储了该对象。是您的表单刷新了页面……可能是原因,但是就您提供的代码而言,一切都按预期进行。

let myLibrary = []

function Book(title,author,pages,read) {
	this.title = title
	this.author = author
	this.pages = pages
	this.read = read
	myLibrary.push(this)
}

function checkForm(name,author,pages,read)
{
  new Book(name,author,pages,read)
}

checkForm("Chris","Jerry","56","65");
checkForm("Sean","John","56","65");

// Both Objects are still stored...
console.log(myLibrary);

0
投票

尽管您的html中有一个表单,但是您必须添加e.preventDefault();以防止单击“提交”按钮时提交它,您的JavaScript似乎运行良好。见下文:

let myLibrary = [];

function Book(title, author, pages, read) {
  this.title = title;
  this.author = author;
  this.pages = pages;
  this.read = read;
  myLibrary.push(this);
}

function checkForm(e) {
  e.preventDefault(); // prevent the form from being submitted
  let name = document.querySelector('input[name="title"]').value;
  let author = document.querySelector('input[name="author"]').value;
  let pages = document.querySelector('input[name="pages"]').value;
  let read = document.querySelector('input[name="read"]').checked;
  new Book(name, author, pages, read);
  console.log(myLibrary);
}

submit.addEventListener("click", checkForm);
<form>
  <input type="text" name="title" />
  <input type="text" name="author" />
  <input type="text" name="pages" />
  <input type="checkbox" name="read" />
  <button id="submit">Submit</button>
</form>

0
投票

您正在监听“提交”按钮上的点击事件,但是“提交”按钮也会提交表单。如果不阻止默认的“提交”事件,则窗体自然会导致刷新。

相反,您可以侦听表单提交事件并阻止它:

// Query select the form and
form.addEventListener('submit', function(e){
        e.preventDefault();
        checkForm();
});
© www.soinside.com 2019 - 2024. All rights reserved.