我正在尝试建立一个图书馆,用户可以在其中编写信息和书籍并将其添加到图书馆。我创建了一个模式表单,用户可以在其中编写信息并提交。
这是模态html
<form class="modal__container">
<div class="modal">
<div class="modal__content">
<label for="">Title:</label>
<input type="text" id="title">
</div>
<div class="modal__content">
<label for="">Author:</label>
<input type="text" id="author">
</div>
<div class="modal__content">
<label for="">Pages:</label>
<input type="number" id="pages">
</div>
<label for="">Have you read it?</label>
<div>
<label for="yes">Yes</label>
<input type="radio" name ="read" value="yes">
<label for="no">No</label>
<input type="radio" name ="read" value="no">
</div>
<button class="add__book">Add</button>
<button class="cancel">Cancel</button>
</div>
</form>
这是单击取消按钮时关闭模式的功能
function toggle() {
addBtn.addEventListener("click", () => {
modal.style.display = "block";
const cancel = document.querySelector(".cancel");
cancel.addEventListener("click", () => {
modal.style.display = "none";
})
})
}
toggle();
这里我有构造函数和数组来存储书籍
let myLibrary = [];
function Book(title, author, pages) {
this.title = title,
this.author = author,
this.pages = pages
}
现在我想创建一个提交新书的函数
submitBook.addEventListener("click", addBookToLibrary);
function addBookToLibrary() {
let bookTitle = modalTitle.value;
let bookAuthor = modalAuthor.value;
let bookPages = modalPages.value;
let book = new Book(bookTitle, bookAuthor, bookPages);
myLibrary.push(book);
console.log(bookTitle)
console.log(bookAuthor)
console.log(bookPages)
toggle();
}
我看到信息半秒钟然后消失了。我知道我应该在某处使用防止默认值。我试过这个
它正确显示信息,但不会关闭模式。我该如何解决?
慕沐林林
相关分类