【发布时间】:2021-03-13 12:37:24
【问题描述】:
只要我单击发出简单警报的按钮,网页就会重置。 仅当从一开始单击不在 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')
}
});
如何解决这个问题,以便我可以简单地折叠表单并允许用户通过再次弹出表单来添加另一本书?
【问题讨论】:
标签: javascript dom event-delegation