【问题标题】:Creating new object instances and pushing them to an array in plain Javascript [duplicate]创建新的对象实例并将它们推送到纯 Javascript 的数组中 [重复]
【发布时间】:2020-07-23 18:50:24
【问题描述】:

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

由于某种原因,数组正在“重置”而不是保存对象。

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)
document.getElementById('library').innerText = JSON.stringify(myLibrary)
}

const submit = document.getElementById('btn1')
submit.addEventListener("click",checkForm);
<input name='title' />
<input name='author' />
<input name='pages' />
<input name='read' />

<button id='btn1'>Click me! </button>
<div >Library:</div>
<div id='library'></div>

【问题讨论】:

  • 您也可以分享您的html 吗?我无法重现,我的html 似乎工作得很好,请在下面查看我的答案。
  • 您的表单是否正在重新加载页面?请在您的问题上提供 html...
  • 这里是其余代码:jsfiddle.net/xdgmjz54/1
  • @heyslevin,是的,您只是错过了阻止默认提交表单,请在下面查看我的答案以获取您的代码的 sn-p。

标签: javascript arrays constructor push


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:

    由于您的html 中有一个表单,因此您必须防止其默认提交事件导致使用preventDefault() 重新加载页面。例如,您可以更改您的checkForm() 并在其中添加e.preventDefault() 以防止表单被提交。

    let myLibrary = []
    
    function Book(title, author, pages, read) {
      this.title = title
      this.author = author
      this.pages = pages
      this.read = read
    }
    
    function addtoLibrary(title, author, pages, read) {
      let book = new Book(title, author, pages, read)
      myLibrary.push(book)
    }
    
    
    let table = document.querySelector(".table");
    
    myLibrary.forEach(function(e) {
      table.innerHTML += `<tr><td>${e.title}</td>
    							<td>${e.author}</td>
    							<td>${e.pages}</td>
    							<td>${e.read}</td>
    						</tr>
    						`
    });
    
    
    // Selectors
    let add = document.querySelector("#add")
    let submit = document.querySelector("#submit")
    
    
    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
      addtoLibrary(name, author, pages, read)
      console.log(myLibrary);
    }
    
    submit.addEventListener("click", checkForm);
    html,
    body {
      height: 100%;
    }
    
    * {
      font-family: Graphik Regular;
    }
    
    ul {
      list-style-type: none;
    }
    
    table,
    th,
    td {
      border-collapse: collapse;
      text-align: left;
      border: 1px solid black;
    }
    
    table {
      width: 100%;
    }
    
    td,
    th {
      height: 50px;
      padding: 10px;
      width: 200px;
      min-width: 100px;
    }
    
    th {
      background-color: gray;
      margin-bottom: 50px;
    }
    
    .headers {
      margin-bottom: 5px;
    }
    
    button {
      background-color: #4CAF50;
      /* Green */
      border: none;
      color: white;
      padding: 15px 32px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      margin-top: 30px;
    }
    
    .pop-container {
      text-align: center;
      /*	display: none;*/
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.6);
    }
    
    form {
      background-color: gray;
    }
    
    input {
      font-size: 20px;
      width: 300px;
      margin-bottom: 5px;
    }
    <!DOCTYPE html>
    
    <meta charset="UTF-8">
    
    <html lang="en">
    
    <head>
      <link rel="stylesheet" type="text/css" href="style.css">
      </stylesheet>
      <script type="text/javascript" src="http://livejs.com/live.js"></script>
    </head>
    
    <body>
    
      <div class="pop-container">
        <form id="bookquery">
          <input type="text" name="title" id="title" placeholder="Title"></br>
          <input type="text" name="author" placeholder="Author"></br>
          <input type="text" name="pages" placeholder="Pages"></br>
          <p>Have you read it?<input type="checkbox" placeholder="Title" name="read"></p>
          </br>
          <button id="submit">Submit</button>
        </form>
      </div>
    
      <table class="headers">
        <th>Title</th>
        <th>Author</th>
        <th>Pages</th>
        <th>Read</th>
      </table>
    
    
      <table class="table tstyle">
      </table>
    
      <button id="add">Add new book</button>
    
    
      <script src="script.js"></script>
    </body>
    
    </html>
    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
      addtoLibrary(name, author, pages, read)
    }
    

    【讨论】:

    • 你是对的,谢谢这完美的工作。花了很长时间不明白为什么 javascript 不工作。现在我明白为什么了。
    【解决方案3】:

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

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

    // Query select the form and
    form.addEventListener('submit', function(e){
            e.preventDefault();
            checkForm();
    });
    

    【讨论】:

    • 这很好用。以为按钮现在什么都不做,直到我添加了 Luís Ramalho 建议的 console.log。感谢您的帮助!
    【解决方案4】:

    上面的答案对我来说不太适用,所以这里有一个简化的、完全有效的例子。作为让这样的事情发挥作用的一般指南,我总是尽量简化。

    index.html

    <html>
      <header></header>
      <body>
        <div>
            <form id="myForm">
                <label for="title">title:</label><br>
                <input type="text" id="title" name="title" value="title"><br>
                <button id="submit">Submit</button>
            </form>
        </div>
        <script type="text/javascript" src="functions.js"></script>
      </body>
    </html>
    

    functions.html

    let myLibrary = [];
    
    function Book(title) {
      this.title = title;
      myLibrary.push(this);
    }
    
    
    function checkForm(){
      let title = document.querySelector('input[name="title"]').value;
      new Book(title);
      myLibrary.forEach(function(element) {
        console.log(element);
      });
    }
    
    document.getElementById("myForm").addEventListener(
      'submit',
      function(e) {
        e.preventDefault();
        checkForm();
      }
    );
    

    我会留给您在 Book 对象的其他字段中添加回。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 2022-01-26
      相关资源
      最近更新 更多