使用数组 JavaScript 更新 DOM

问题描述

当我尝试使用来自 API 的新信息更新 DOM 时遇到问题。

每次我点击添加新用户时,数组都会显示旧信息和新信息。理想情况下,它会先更新数组,然后仅显示新信息。我将附上正在发生的事情的图片。我希望每次用户点击添加新用户时,DOM 更新仅包含该新用户的信息。

HTML 部分

<table class="table is-fullwidth table is-hoverable table-info">
   <thead>
          <tr">
              <th title="Channel Name" class="has-text-left"> Channel Name </th>
              <th title="View per week" class="has-text-right"> View per week </th>
          </tr>
   </thead>
   <tbody id="body-table">
          <tr id="tr-table">

          </tr> 
    </tbody>
</table>

script.js

const trline = document.getElementById('body-table')


let usersList = [];

async function getnewUsers(){
    const res = await fetch('https://randomuser.me/api')
    const data = await res.json()
    // create an instance of the results
    const user = data.results[0]
    // create the new user
    const newUser = {
        name:`${user.name.first} ${user.name.last}`,social: Math.floor(Math.random() * 10000 )
    }
    // update the new user to the database...
    addData(newUser)  
}

function addData(obj) {
    usersList.push(obj)
    // update the information on the screen
    updateDOM()
}

function updateDOM( providedData = usersList){
    providedData.forEach(item => {
        const element = document.createElement('tr')
        element.innerHTML = `
        <td class="has-text-left cname"> ${item.name} </td>
        <td class="has-text-right cview"> ${item.social} k</td>
        `
        trline.appendChild(element)
    })
}

addUser.addEventListener('click',getnewUsers)

结果图片

loop same information

解决方法

我找到了问题和解决方案。 在添加新项目之前,我没有重置 HTML 部分以清除。我不得不用这个修复函数 updateDOM:trline.innerHTML = ''

此后,该功能工作正常。

function updateDOM( providedData = usersList){
trline.innerHTML = '' // clear everything before adding new stuff

providedData.forEach(item => {
    const element = document.createElement('tr')
    element.innerHTML = `
    <td class="has-text-left cname"> ${item.name} </td>
    <td class="has-text-right cview"> ${item.social} k</td>
    `
    trline.appendChild(element) 
})

}