单击按钮重置网页

Button click resets a web page

只要我点击发出简单警报的按钮,网页就会重置。 仅当从头开始单击不在 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')
    }
});

对于大多数浏览器来说,默认的按钮类型是提交。将 type 属性 添加到按钮,可以对其进行编程以在分配事件处理函数(通常用于单击事件)时控制自定义功能。

<button type="button" id="submit-button">SUBMIT</button>