我正在创建一个简单的书单应用。它具有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();
});