javascript - 关于使用 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();
});
解决方案
推荐阅读
- javascript - 如何根据php中的前2个输入字段选择值
- java - 无法从我的 WebView 在 Whatsapp 上分享。无法加载位于 whatsapp://send?text= 的网页,因为 net::ERR_UNKNOWN_URL_SCHEME
- angular - 是否可以使 mat-button-toggle-group 响应?
- python - 常数 e 的连分数
- php - 如何从 MySQL 表中选择消息列表?
- visual-studio-code - 如何在 VSCode 中一次重新映射所有 ctrl+k 和弦
- dart - 可选参数的默认值必须是常量
- javascript - Sort array by year and month
- php - 在 laravel 中配置 redis_host
- intellij-idea - `Error:osgi: [optaplanner-core] Unexpected build error` 构建 CloudBalancingHelloWorld