我试图建立一个库,用户可以写信息和书,并将其添加到库中。 我创建了一个模式表单,用户可以在其中写入信息并提交它。
这是模式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();
}
我看到信息半秒钟后就消失了。 我知道我应该在某处使用防止违约。 我试过了
function addBookToLibrary(e) {
e.preventDefault();
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();
}
它正确地显示信息,但它不关闭模式。 我该怎么修好呢?
您当前有一个匿名函数,它可以做您想做的事情:关闭模式。 它位于另一个匿名函数中,该函数打开模式:
addBtn.addEventListener("click", () => {
modal.style.display = "block";
const cancel = document.querySelector(".cancel");
cancel.addEventListener("click", () => {
modal.style.display = "none";
});
});
您可以从该代码中“重构”出两个命名函数,如下所示:
const hideModal = () => {
modal.style.display = "none";
};
const showModal = () => {
modal.style.display = "block";
const cancel = document.querySelector(".cancel");
cancel.addEventListener("click", hideModal);
};
addBtn.addEventListener("click", showModal);
然后,在其他事件处理程序中,可以调用任一函数:
function addBookToLibrary() {
// ...
hideModal();
}