简体   繁体   English

通过 JavaScript 动态添加 HTML 部分会在刷新时复制 HTML 代码

[英]Dynamically adding an HTML section via JavaScript duplicates the HTML code on refresh

I am trying to resolve a course project of mine and I am having hard time with one of the functionalities.我正在尝试解决我的课程项目,但我很难使用其中一个功能。 I have a piece that should fetch and display all entries from a Firebase DB but what it does on refresh is to add one more to the DOM (no change in Firebase) instead of simply returning the Firebase results.我有一块应该从 Firebase 数据库中获取并显示所有条目,但它在刷新时所做的是向 DOM 添加一个(Firebase 中没有变化),而不是简单地返回 Firebase 结果。

 const data = { "-MQufI6df_3HJ6WQtB0u": { "author": "Test", "isbn": "123", "title": "Testing1" }, "-MQufLMu5gGKQlZE0UrN": { "author": "Test", "isbn": "123", "title": "Testing2" }, "-MQufLwiyLP6T3pXHKH5": { "author": "Test", "isbn": "123", "title": "Testing3" } } document.getElementById('loadBooks').addEventListener('click', function() { document.getElementById('booksList').innerHTML = ''; let books = Object.entries(data); for (const book in books) { console.log(book); let currentBook = books[book][1]; let newBook = document.createElement('tr'); newBook.innerHTML = ` <tr> <td>${currentBook.title}</td> <td>${currentBook.author}</td> <td>${currentBook.isbn}</td> <td style="display: none">${books[book][0]}</td> <td> <button>Edit</button> <button>Delete</button> </td> </tr> `; document.getElementById('booksList').appendChild(newBook); } });
 <button id="loadBooks">LOAD ALL BOOKS</button> <table> <thead> <tr> <th>Title</th> <th>Author</th> <th>Isbn</th> <th>Action</th> </tr> </thead> <tbody id="booksList"> </tbody> </table> <form> <h3>FORM</h3> <label>TITLE</label> <input type="title" id="title" placeholder="Title..."> <label>AUTHOR</label> <input type="title" id="author" placeholder="Author..."> <label>ISBN</label> <input type="title" id="isbn" placeholder="Isnb..."> <button id="submit">Submit</button> </form>

Current result: Lets say I have 1 book: Book - John Smith - 1234当前结果:假设我有 1 本书:Book - John Smith - 1234

After hitting again the 'loadBooks;'再次点击“loadBooks”之后; btn I see in the browser: Book - John Smith - 1234 Book - John Smith - 1234 btn 我在浏览器中看到: Book - John Smith - 1234 Book - John Smith - 1234

Expected result: On refresh I should only see: Book - John Smith - 1234预期结果:刷新时我应该只看到:Book - John Smith - 1234

until I add a second book to my list.直到我将第二本书添加到我的列表中。

you need to simply add one check before appending child 'newBook' in 'booksList'您只需在“booksList”中添加子“newBook”之前添加一张支票

var booksList = document.getElementById("booksList");
if(booksList !== null){ // thats means its exists in dom
   document.getElementById('booksList).innerHTML = ''
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM