首页 > 解决方案 > 关于使用 eventListener 实例化函数构造函数的问题

问题描述

我正在创建一个简单的书单应用程序。它有 3 个输入字段(标题、作者和 isbn)。我在表单元素上有一个提交事件。我可能有脑子放屁什么的,但我很好奇我如何能够在每次触发提交事件时实例化一本新书( const book = new Book(title, author, isbn); )。我不会一遍又一遍地声明同一个变量吗?我假设的简单答案,但对于我的生活,我不记得这是如何工作的。

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

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

  // Instantiate a UI Object
  const ui = new UI();

  debugger;

  // Validate
  if(title === '' || author === '' || isbn === '') {
    // Error alert
    ui.showAlert('Please fill in all fields', 'error');
  } else {
    // Add book to list
    ui.addBookToList(book);
    // Show success
    ui.showAlert('Book Added!', 'success');
    // Clear inputs
    ui.clearInputs();
  }

  e.preventDefault();
});

标签: javascriptfunctioneventsprototypeinstantiation

解决方案


推荐阅读