如何使用带 JavaScript 的 DOMContentLoaded 显示我的本地存储的内容

How to display the content of my Local Storage using DOMContentLoaded with JavaScript

我正在开发一个图书馆应用程序,我需要在主页上显示我本地存储的内容。我知道如何获取书籍数组,但我很难尝试在 table.

内的页面上显示它

当用户单击表单上的提交按钮 (addBookToList()) 时,table 在另一个函数中创建。

有没有一种方法可以在用户重新加载页面时重用相同的功能并在相同的 table 上显示本地存储中的书籍?

HTML:

    <form action="#" class="form">
        <label for="title">Title</label>
        <input type="text" id="title" required>
        <label for="author">Author</label>
        <input type="text" id="author" required>
        <label for="num-pages">No. of pages</label>
        <input type="number" id="num-pages" required>
        <br>
        <span>Have you read this book?</span>
        <br>
        <input type="radio" name="radio" id="yes" value="yes" checked>
        <label for="yes" class="yes">Yes</label>
        <input type="radio" name="radio" id="no" value="no">
        <label for="no" class="no">No</label>
        <div class="button-div">
            <button id="add-btn" type="submit">SUBMIT</button>
        </div>
    </form>
</div>

<div class="table-box">
    <hr>
    <table>
        <thead>
            <tr>
                <th>Title</th>
                <th>Author</th>
                <th>No. of pages</th>
                <th>Read</th>
            </tr>
        </thead>
        <tbody class="list"></tbody>

    </table>
</div>

JAVASCRIPT:

// Get values
let formContainer = document.querySelector('.form-div');
let form = document.querySelector('.form');
let addBtn = document.querySelector('#add-btn');
let btnNewBook = document.querySelector('#addBook-btn');

// Book constructor
function Book(author, title, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}

// Empty array to store books
let myLibrary = [];

// Form event listener
form.addEventListener('submit', (e) => {
e.preventDefault();

  // Hide form and show home page
  document.querySelector('.table-box').style.display = 'block';
  document.querySelector('.para-div').style.display = 'block';
  form.style.display = 'none';

  // Get values from User
  let title = document.querySelector('#title').value;
  let author = document.querySelector('#author').value;
  let pages = document.querySelector('#num-pages').value;
  let read = getRead();

  // Instantiate book
  const book = new Book(author, title, pages, read);

  // Push book to the library, show it on the UI and clear the form
  myLibrary.push(book);

  addBookToList();

  // Add book to Local Storage
  addBook();

  // Show success alert
  showAlert('Book added!', 'success');

  // Clear form
  form.reset();

});

// Add book to list
function addBookToList() {
  const list = document.querySelector('.list');

  // Create new row element
  const row = document.createElement('tr');

  // Loop through myLibrary array
  myLibrary.forEach(value => {

    // Add the book to the table
        row.innerHTML = `
        <td>${value.title}</td>
        <td>${value.author}</td>
        <td>${value.pages}</td>
        <td>${value.read}</td>
        <td><a href="#" class="btn delete">X</a></td>`;
});

// Append the row to list
list.appendChild(row);
}

// Storage
function getLibrary() {
   if(localStorage.getItem('myLibrary') === null) {
     myLibrary = [];
   } else {
     myLibrary = JSON.parse(localStorage.getItem('myLibrary'));
   }
   return myLibrary;
 }

 function addBook() {
   localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
 }

 function removeBook(index) {
   getLibrary();
   let removed = myLibrary.indexOf(index);
   myLibrary.splice(removed, 1);
   localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
 }

 // Load page event listener
 document.addEventListener('DOMContentLoaded', function displayBooks(){

   getLibrary();
   addBookToList();

 });

我会说我根本不喜欢你的编码风格......但这是一个简单的解决方案,在我看来并不是最佳的。

document.addEventListener('DOMContentLoaded', ()=>{
  const list = document.querySelector('.list'); // why get it again
  getLibrary();
  let row;
  for(let b of myLibrary){ // I like this kind of loop since you can break out of it if needed
    row = document.createElement('tr'); // new instance at each step of loop
    row.innerHTML = `<td>${b.title}</td>
      <td>${b.author}</td>
      <td>${b.pages}</td>
      <td>${b.read}</td>
      <td><a href="#" class="btn delete">X</a></td>`;
    }
    list.appendChild(row);
  }
});