JS OOP bookstore ES5&ES6

本文介绍了一个基于Skeleton框架的图书管理UI实现,利用HTML、CSS和JavaScript构建了一个可以添加、显示和删除图书的列表应用,并整合了LocalStorage来持久化存储图书数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

UI设置

skeleton https://cdnjs.com/libraries/skeleton

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" />
  <style>
    .success,.error{
      color:white;
      padding: 5px;
      margin: 5px 0 15px 0;
    }
    .success{
      background-color: green;
    }
    .error{
      background-color: red;
    }
  </style>
  <title>BookList</title>
</head>
<body>
  <div class="container">
    <h1>Add Book</h1>
    <form id="book-form">
      <div>
        <label for="title">Title</label>
        <input type="text" id="title" class="u-full-width">
      </div>
      <div>
        <label for="author">Author</label>
        <input type="text" id="author" class="u-full-width">
      </div>
      <div>
        <label for="isbn">ISBN#</label>
        <input type="text" id="isbn" class="u-full-width">
      </div>
      <div>
        <input type="submit" value="Submit" class='u-full-width'>
      </div>
    </form>
    <table class="u-full-width">
      <thead>
        <tr>
          <th>Title</th>
          <th>Author</th>
          <th>ISBN</th>
          <th></th>
        </tr>
      </thead>
      <tbody id='book-list'></tbody>
    </table>
  </div>
  <script src="app.js"></script>
</body>
</html>

在这里插入图片描述

功能——往list中加入book

设置book类

//Book Constructor
function Book(title,author,isbn){
  this.title = title;
  this.author = author;
  this.isbn=isbn;
}

设置UI类

//UI Constructor
function UI(){}

UI类中加入prototype

//Add Book to List
UI.prototype.addBookToList=function(book){
  const list = document.getElementById('book-list');
  //Create tr element
  const row = document.createElement('tr');
  //Insert cols
  row.innerHTML=`
    <td>${book.title}</td>
    <td>${book.author}</td>
    <td>${book.isbn}</td>
    <td><a href="#" class="delete">X<a></td>
  `;
  list.appendChild(row);
}

//Clear Fields
UI.prototype.clearFields=function(){
  document.getElementById('title').value="";
  document.getElementById('author').value="";
  document.getElementById('isbn').value="";
}

对form的submit加入事件

//Event Listeners
document.getElementById('book-form').addEventListener('submit',function(e){
  //get form values
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value;

  //Instantiating a book
  const book = new Book(title,author,isbn);
      
  //Instantiate UI
  const ui = new UI();


  //Add book to list
  ui.addBookToList(book);

  console.log(ui);

  //Clear fields
  ui.clearFields();
      
  e.preventDefault();
})

加入alert——加入失败&成功

//Show alert
UI.prototype.showAlert= function(msg,className){
  //Create div
  const div=document.createElement('div');
  //Add className
  div.className=`alert ${className}`;
  //Add text
  div.appendChild(document.createTextNode(msg));
  //Get parent
  const container = document.querySelector('.container');
  //Get form
  const form = document.querySelector('#book-form');
  //Insert alert
  container.insertBefore(div,form);  //插入的parent.(插入的东西,插入的位置)

  //Timeout after 3 sec
  setTimeout(function(){
    document.querySelector('.alert').remove()  //remove需要()
  },3000);

}

//Event Listeners
document.getElementById('book-form').addEventListener('submit',function(e){
  //get form values
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value;

  //Instantiating a book
  const book = new Book(title,author,isbn);
      
  //Instantiate UI
  const ui = new UI();


  //Validate
  if(title==='' || author === '' ||isbn ===''){
    //Error alert   msg + class
    ui.showAlert('Please fill in all fields','error');
  } else{

  //Add book to list
  ui.addBookToList(book);

  //Show success
  ui.showAlert('Book Added!','success');
  //Clear fields
  ui.clearFields();
  }
  e.preventDefault();
})

增加删除功能

//Delete book
UI.prototype.deleteBook=function(target){
    target.parentElement.parentElement.remove();
}
//Event Listener for delete
document.getElementById('book-list').addEventListener('click',function(e){
  const ui = new UI();
  

  //Show message
  if(e.target.className==='delete'){
    ui.deleteBook(e.target);
    ui.showAlert(`Book removed!`,`success`);
  }
  e.preventDefault();
});  //用parent

ES5

//Book Constructor
function Book(title,author,isbn){
  this.title = title;
  this.author = author;
  this.isbn=isbn;
}


//UI Constructor
function UI(){}

let timeout=null;
//Add Book to List
UI.prototype.addBookToList=function(book){
  const list = document.getElementById('book-list');
  //Create tr element
  const row = document.createElement('tr');
  //Insert cols
  row.innerHTML=`
    <td>${book.title}</td>
    <td>${book.author}</td>
    <td>${book.isbn}</td>
    <td><a href="#" class="delete">X<a></td>
  `;
  list.appendChild(row);
}

//Show alert
UI.prototype.showAlert= function(msg,className){
  
  //Create div
  const div=document.createElement('div');
  //Add className
  div.className=`alert ${className}`;
  //Add text
  div.appendChild(document.createTextNode(msg));
  //Get parent
  const container = document.querySelector('.container');
  //Get form
  const form = document.querySelector('#book-form');
  //Insert alert
  container.insertBefore(div,form);  //插入的parent.(插入的东西,插入的位置)
  clearTimeout(timeout);
  //Timeout after 3 sec
  timeout = setTimeout(function(){
    document.querySelector('.alert').remove()  //remove需要()
  },3000);
}

//Delete book
UI.prototype.deleteBook=function(target){
    target.parentElement.parentElement.remove();
}


//Clear Fields
UI.prototype.clearFields=function(){
  document.getElementById('title').value="";
  document.getElementById('author').value="";
  document.getElementById('isbn').value="";
}

//Clear alert
UI.prototype.clearAlert=function(){
  while(document.getElementsByClassName('alert')[0]!=null){
    document.getElementsByClassName('alert')[0].remove();
  }
}

//Event Listeners for add book
document.getElementById('book-form').addEventListener('submit',function(e){ 
  //get form values
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value;

  //Instantiating a book
  const book = new Book(title,author,isbn);
      
  //Instantiate UI
  const ui = new UI();
  
  //Clear alert
  ui.clearAlert();
  
  //Validate
  if(title==='' || author === '' ||isbn ===''){
    //Error alert   msg + class
    ui.showAlert('Please fill in all fields','error');
  } else{

  //Add book to list
  ui.addBookToList(book);

  //Show success
  ui.showAlert('Book Added!','success');
  //Clear fields
  ui.clearFields();
  }
  e.preventDefault();
});


//Event Listener for delete
document.getElementById('book-list').addEventListener('click',function(e){
  const ui = new UI();
  

  //Show message
  if(e.target.className==='delete'){
    ui.clearAlert();
    ui.deleteBook(e.target);
    ui.showAlert(`Book removed!`,`success`);
  }
  e.preventDefault();
});  //用parent

ES5+Local Storage

//输入
document.addEventListener('DOMContentLoaded',displaybooks);
function getbooks(){
  let books;
  if(localStorage.getItem('books')==null) books=[];
  else books=JSON.parse(localStorage.getItem('books'));
  return books;
}
function displaybooks(){
  const books=getbooks();
  books.forEach(function(book){
    const ui=new UI();
    ui.addBookToList(book);
  })
}
function addbooks(book){
  const books=getbooks();
  books.push(book);
  localStorage.setItem('books',JSON.stringify(books));
}
function deletebooks(isbn){
  const books=getbooks();
  books.forEach(function(book,index){
    if(book.isbn===isbn) {
      books.splice(index,1);
    }
  })
  localStorage.setItem('books',JSON.stringify(books));
}



//Book Constructor
function Book(title,author,isbn){
  this.title = title;
  this.author = author;
  this.isbn=isbn;
}


//UI Constructor
function UI(){}

let timeout=null;
//Add Book to List
UI.prototype.addBookToList=function(book){
  const list = document.getElementById('book-list');
  //Create tr element
  const row = document.createElement('tr');
  //Insert cols
  row.innerHTML=`
    <td>${book.title}</td>
    <td>${book.author}</td>
    <td>${book.isbn}</td>
    <td><a href="#" class="delete">X<a></td>
  `;
  list.appendChild(row);
}

//Show alert
UI.prototype.showAlert= function(msg,className){
  
  //Create div
  const div=document.createElement('div');
  //Add className
  div.className=`alert ${className}`;
  //Add text
  div.appendChild(document.createTextNode(msg));
  //Get parent
  const container = document.querySelector('.container');
  //Get form
  const form = document.querySelector('#book-form');
  //Insert alert
  container.insertBefore(div,form);  //插入的parent.(插入的东西,插入的位置)
  clearTimeout(timeout);
  //Timeout after 3 sec
  timeout = setTimeout(function(){
    document.querySelector('.alert').remove()  //remove需要()
  },3000);
}

//Delete book
UI.prototype.deleteBook=function(target){
    target.parentElement.parentElement.remove();
}


//Clear Fields
UI.prototype.clearFields=function(){
  document.getElementById('title').value="";
  document.getElementById('author').value="";
  document.getElementById('isbn').value="";
}

//Clear alert
UI.prototype.clearAlert=function(){
  while(document.getElementsByClassName('alert')[0]!=null){
    document.getElementsByClassName('alert')[0].remove();
  }
}

//Event Listeners for add book
document.getElementById('book-form').addEventListener('submit',function(e){ 
  //get form values
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value;

  //Instantiating a book
  const book = new Book(title,author,isbn);
      
  //Instantiate UI
  const ui = new UI();
  
  //Clear alert
  ui.clearAlert();
  
  //Validate
  if(title==='' || author === '' ||isbn ===''){
    //Error alert   msg + class
    ui.showAlert('Please fill in all fields','error');
  } else{

  //Add book to list
  ui.addBookToList(book);
  addbooks(book);  //放在这儿才行//放在add里面就循环添加了;
  //Show success
  ui.showAlert('Book Added!','success');
  //Clear fields
  ui.clearFields();
  }
  e.preventDefault();
});


//Event Listener for delete
document.getElementById('book-list').addEventListener('click',function(e){
  const ui = new UI();
  deletebooks(e.target.parentElement.previousElementSibling.textContent);

  //Show message
  if(e.target.className==='delete'){
    ui.clearAlert();
    ui.deleteBook(e.target);
    ui.showAlert(`Book removed!`,`success`);
  }
  e.preventDefault();
});  //用parent


//加入local storage


ES6

class Book{
  constructor(title,author,isbn){
    this.title=title;
    this.author=author;
    this.isbn=isbn;
  }
}
let timeout=null; //设为全局变量
class UI{
  addBookToList(book){
    const list = document.getElementById('book-list');
    //Create tr element
    const row = document.createElement('tr');
    //Insert cols
    row.innerHTML=`
      <td>${book.title}</td>
      <td>${book.author}</td>
      <td>${book.isbn}</td>
      <td><a href="#" class="delete">X<a></td>
    `;
    list.appendChild(row);
  }
  showAlert(message,className){
      //Create div
      const div=document.createElement('div');
      //Add className
      div.className=`alert ${className}`;
      //Add text
      div.appendChild(document.createTextNode(message));
      //Get parent
      const container = document.querySelector('.container');
      //Get form
      const form = document.querySelector('#book-form');
      //Insert alert
      container.insertBefore(div,form);  //插入的parent.(插入的东西,插入的位置)
      //Timeout after 3 sec
      timeout = setTimeout(function(){
        if(document.querySelector('.alert')!=null)
        document.querySelector('.alert').remove()  //remove需要()
      },3000);
  }
  deleteBook(target){
    target.parentElement.parentElement.remove();
  }
  clearFields(){
    document.getElementById('title').value="";
    document.getElementById('author').value="";
    document.getElementById('isbn').value="";
  }
  clearAlert(){
    while(document.querySelector('.alert')!=null)
    document.querySelector('.alert').remove();
  }
}

document.getElementById('book-form').addEventListener('submit',function(e){ 
  //get form values
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value;

  //Instantiating a book
  const book = new Book(title,author,isbn);
      
  //Instantiate UI
  const ui = new UI();
  clearTimeout(timeout);
  //Clear alert
  ui.clearAlert();
  
  //Validate
  if(title==='' || author === '' ||isbn ===''){
    //Error alert   msg + class
    ui.showAlert('Please fill in all fields','error');
  } else{

  //Add book to list
  ui.addBookToList(book);

  //Show success
  ui.showAlert('Book Added!','success');
  //Clear fields
  ui.clearFields();
  }
  e.preventDefault();
});


//Event Listener for delete
document.getElementById('book-list').addEventListener('click',function(e){
  const ui = new UI();
  

  //Show message
  if(e.target.className==='delete'){
    ui.clearAlert();
    ui.deleteBook(e.target);
    ui.showAlert(`Book removed!`,`success`);
  }
  e.preventDefault();
});  //用parent

ES6+Local Storage

class Book{
  constructor(title,author,isbn){
    this.title=title;
    this.author=author;
    this.isbn=isbn;
  }
}
let timeout=null; //设为全局变量
class UI{
  addBookToList(book){
    const list = document.getElementById('book-list');
    //Create tr element
    const row = document.createElement('tr');
    //Insert cols
    row.innerHTML=`
      <td>${book.title}</td>
      <td>${book.author}</td>
      <td>${book.isbn}</td>
      <td><a href="#" class="delete">X<a></td>
    `;
    list.appendChild(row);
  }
  showAlert(message,className){
      //Create div
      const div=document.createElement('div');
      //Add className
      div.className=`alert ${className}`;
      //Add text
      div.appendChild(document.createTextNode(message));
      //Get parent
      const container = document.querySelector('.container');
      //Get form
      const form = document.querySelector('#book-form');
      //Insert alert
      container.insertBefore(div,form);  //插入的parent.(插入的东西,插入的位置)
      //Timeout after 3 sec
      timeout = setTimeout(function(){
        if(document.querySelector('.alert')!=null)
        document.querySelector('.alert').remove()  //remove需要()
      },3000);
  }
  deleteBook(target){
    target.parentElement.parentElement.remove();
  }
  clearFields(){
    document.getElementById('title').value="";
    document.getElementById('author').value="";
    document.getElementById('isbn').value="";
  }
  clearAlert(){
    while(document.querySelector('.alert')!=null)
    document.querySelector('.alert').remove();
  }
}

//Local storage Class
class Store{
  static getBooks(){ //从LS中得到
    let books;
    if(localStorage.getItem('books')===null)books = [];
    else books = JSON.parse(localStorage.getItem('books'));
    return books;
  }
  static displayBooks(){
    const books=Store.getBooks();

    books.forEach(function(book){
      const ui = new UI();
      //Add book to ui
      ui.addBookToList(book);
    })
  }
  static addBook(book){
    const books = Store.getBooks(); //static methods
    books.push(book);
    localStorage.setItem('books',JSON.stringify(books));
  }
  static removeBook(isbn){
    const books = Store.getBooks(); //static methods
    books.forEach(function(book,index){
      if(book.isbn==isbn){
        books.splice(index,1);
      }
    });
    localStorage.setItem('books',JSON.stringify(books));
  }
}

//Dom load event
document.addEventListener('DOMContentLoaded',Store.displayBooks);

document.getElementById('book-form').addEventListener('submit',function(e){ 
  //get form values
  const title = document.getElementById('title').value,
        author = document.getElementById('author').value,
        isbn = document.getElementById('isbn').value;

  //Instantiating a book
  const book = new Book(title,author,isbn);
      
  //Instantiate UI
  const ui = new UI();
  clearTimeout(timeout);
  //Clear alert
  ui.clearAlert();
  
  //Validate
  if(title==='' || author === '' ||isbn ===''){
    //Error alert   msg + class
    ui.showAlert('Please fill in all fields','error');
  } else{

  //Add book to list
  ui.addBookToList(book);
  //Add to local storage
  Store.addBook(book);

  //Show success
  ui.showAlert('Book Added!','success');
  //Clear fields
  ui.clearFields();
  }
  e.preventDefault();
});


//Event Listener for delete
document.getElementById('book-list').addEventListener('click',function(e){
  const ui = new UI();
  

  //Show message
  if(e.target.className==='delete'){
    ui.clearAlert();
    ui.deleteBook(e.target);
    //Remove from LS
    Store.removeBook(e.target.parentElement.previousElementSibling.textContent);

    ui.showAlert(`Book removed!`,`success`);
  }
  e.preventDefault();
});  //用parent
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值