javascript - 如何在函数内使用防止默认和切换?
问题描述
我正在尝试建立一个图书馆,用户可以在其中编写信息和书籍并将其添加到图书馆。我创建了一个模式表单,用户可以在其中编写信息并提交。
这是模态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();
}
推荐阅读
- javascript - HTML-如何自动生成无限不同的模态?
- node.js - 数据没有被推送到主模式数组猫鼬中
- codeigniter - 演示中禁用数据编辑
- python-3.x - 需要优化此代码,以 y 坐标的降序对坐标进行排序
- r - 在数据框中添加重复的行
- java - 导入 net.sf.jasperreports.view;导入 net.sf.jasperreports.engine;如何获取这个jar文件
- java - 如何限制Java程序中的多线程?
- java - 为什么 Pitest 在命令行上与 maven 一起工作,但在 Jenkins-Pipeline 中却不行?
- laravel-5.4 - 更改项目目录名称后邮件不发送
- python - 如何从聊天机器人的输入文本中提取日期?