亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在函數內使用防止默認和切換?

如何在函數內使用防止默認和切換?

料青山看我應如是 2022-10-13 10:50:40
我正在嘗試建立一個圖書館,用戶可以在其中編寫信息和書籍并將其添加到圖書館。我創建了一個模式表單,用戶可以在其中編寫信息并提交。這是模態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();}我看到信息半秒鐘然后消失了。我知道我應該在某處使用防止默認值。我試過這個它正確顯示信息,但不會關閉模式。我該如何解決?
查看完整描述

1 回答

?
慕沐林林

TA貢獻2016條經驗 獲得超9個贊

您當前有一個匿名函數可以執行您想要的操作:關閉模式。它在另一個打開模式的匿名函數中:


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

}


查看完整回答
反對 回復 2022-10-13
  • 1 回答
  • 0 關注
  • 104 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號