【问题标题】:Updating the DOM with arrays JavaScript使用数组 JavaScript 更新 DOM
【发布时间】:2021-05-07 23:04:49
【问题描述】:

当我尝试使用来自 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)

结果图片:

【问题讨论】:

  • 你为什么“传递”用户作为默认值而不是updateDOM(usersList)? o.O
  • 在从providedData 追加元素之前删除现有的表行,或者添加一个每次只添加一个用户的方法(来自addData() 的那个)。
  • 如果我决定添加一个方法来一次添加一个,我会怎么做?
  • updateDOM() 一样,只是没有循环。

标签: javascript arrays dom foreach dom-events


【解决方案1】:

我找到了问题和解决方案。 在添加新项目之前,我没有将 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) 
})

}

【讨论】:

  • 我不推荐使用innerHTML 来更新DOM。你会从使用element.appendChild等方法中学到很多东西
猜你喜欢
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
  • 2015-03-30
  • 2017-02-09
  • 1970-01-01
  • 2015-05-29
  • 2016-07-20
  • 2018-01-12
相关资源
最近更新 更多