【发布时间】: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