单击按钮重置网页

makePeaze

一旦我单击发出简单警报的按钮,网页就会重置。仅当单击一开始不在 DOM 中的按钮时才会出现问题。

function addNewBook (book, author, pages) {
    // Add inputs and labels to the HTML form
    document.getElementById('book-form').innerHTML = 
    `<label for="book">Name</label><br>
    <input type="text"><br>
    <label for="author">Author</label><br>
    <input type="text"><br>
    <label for="pages">Pages</label><br>
    <input type="text"><br>
    <div id="button-div">
        <button id="submit-button">SUBMIT</button>
    </div>`
}

// Adding eventlistener to already-existing button that
// triggers the creation of the next button
document.getElementById("new-book-button").addEventListener("click", function () {
    addNewBook("goodName", "goodAuthor", "540")
});

// When this button is clicked, the webpage is reset, 
// the book + form created by the addNewBook function are removed.
// Event delegation used since button is not in the DOM from the beginning.
document.querySelector('body').addEventListener('click', event => {
    if (event.target.matches('#submit-button')) {
        alert('hi')
    }
});

我如何解决这个问题,以便我可以简单地折叠表单并允许用户通过再次弹出表单来添加另一本书?

传教士

只需添加 event.preventDefault();

document.querySelector('body').addEventListener('click', event => {
    if (event.target.matches('#submit-button')) {
event.preventDefault();
        alert('hi')
    }
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章