首页 > 解决方案 > 按下按钮后循环遍历对象数组

问题描述

我正在尝试遍历对象数组,以根据我的库项目的输入值在网格上显示它们。我的循环代码是

const addBook = (ev) => {
    ev.preventDefault();
    let myLibrary = [];
    let bookInfo = {
      title: document.getElementById('title').value,
      author: document.getElementById('author').value,
      pages: document.getElementById('pages').value,
    }
    myLibrary.push(bookInfo)
    for (i = 0; i < myLibrary.length; i++) {
      console.log(myLibrary)
      var container = document.getElementById('book-shelf')
      var div = document.createElement('div')
      div.classList.add('cell')
      container.appendChild(div);
    }
    var submitBtn = document.querySelector('.submit-btn');
    submitBtn.addEventListener('click', addBook)

每次我输入标题、作者和页面值并单击提交按钮时,它都会通过并给我一个单元格。如果尝试添加另一本书,它给了我 3 个单元格而不是 2 个。再添加一个单元格给我 6 个而不是 3 个。我怎样才能让它每次都可以添加一本书而不是多次添加?

标签: javascripthtmlcss

解决方案


主要有三个问题。

  1. 在函数之后和按钮侦听器之前缺少大括号。

  2. myLibrary每次调用函数时都会重新定义,这是您每次都必须查看数据的原因之一。您想在函数外部定义它,以便在addBook调用时一次添加一本书。

  3. 不再myLibrary需要每次都重新定义循环。我们可以将这本书的 HTML 添加到书架上onSubmit

(注意:在这个工作示例中(我为表格、输入和按钮添加了一些 HTML,并创建了一些代码来将新书添加到书架上),我已将myLibrary变量重命名为bookShelf以保持一致HTML 命名。)

// Cache all the elements up front
const titleEl = document.getElementById('title');
const authorEl = document.getElementById('author');
const pagesEl = document.getElementById('pages');
const bookshelfEl = document.getElementById('bookshelf');
const submitBtn = document.querySelector('.submit-btn');

// Add the listener
submitBtn.addEventListener('click', addBook, false);

titleEl.focus();

// Our bookShelf variable is now
// outside the function
const bookShelf = [];

function addBook() {

  // Because we've cached the elements
  // we can now just grab the values from each
  const bookInfo = {
    title: titleEl.value,
    author: authorEl.value,
    pages: pagesEl.value,
  }

  bookShelf.push(bookInfo);

  // Once we've added our book we can grab the
  // title, author, and pages variables from it
  const { title, author, pages } = bookInfo;

  // Create a row for the table
  const row = document.createElement('tr')

  // Create some HTML and add it to the div
  row.innerHTML = `
     <td>${title}</td>
     <td>${author}</td>
     <td>${pages}</td>
  `;

  bookshelfEl.appendChild(row);

}
table { border-collapse: collapse; border: 2px solid #565656; width: 100%; }
td { text-align: center; }
.heading { background-color: #efefef; border-top: solid thin #565656; }
tr { border: solid thin #ababab; }
<input placeholder="Title" id="title" />
<input placeholder="Author" id="author" />
<input placeholder="Pages" id="pages" />
<button type="button" class="submit-btn">Submit</button>
<H3>Book shelf</H3>
<table>
  <tbody id="bookshelf">
    <tr class="heading">
      <td>Title</td>
      <td>Author</td>
      <td>Pages</td>
    </tr>
  </tbody>
</table>

附加文件


推荐阅读