首页 > 解决方案 > 如何在函数内使用防止默认和切换?

问题描述

我正在尝试建立一个图书馆,用户可以在其中编写信息和书籍并将其添加到图书馆。我创建了一个模式表单,用户可以在其中编写信息并提交。

这是模态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();

}

它正确显示信息,但不会关闭模式。我该如何解决?

标签: javascriptpreventdefault

解决方案


您当前有一个匿名函数可以执行您想要的操作:关闭模式。它在另一个打开模式的匿名函数中:

 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();
}

推荐阅读