繁体   English   中英

如何 append 将一行插入到表中,其中包含先前从 JSON 获取并解析为 object 的 td{element) 数据

[英]How to append a row to a table with td{element) data previously fetched from JSON and parsed into an object

I fetched JSON and parsed it into an object which I passed to a function that will add a row for each object and it's specific data

fetch('gamesApi.json')
  .then((response)=>{
    return response.json();
  })
  .then((result)=>{
    displayGamesObject(result,displayGames);
  })
  .catch(()=>{
    console.log(new Error('Error Occurred.'));
  });

然后我有这两个功能

function displayGamesObject(gameObjects,callback) {
  gameObjects.forEach(game => {           
    callback(game)
  });
}

function displayGames(game) {

  document.getElementById('game-list-table').insertAdjacentHTML('afterend',`
<tr>
  <td>${game.id}</td>
  <td> <a href=${game.url} target="_blank"><img src=${game.photo} alt="Photo"></a> </td>
  <td>${game.name}</td>
  <td>${game.publisher}</td>
  <td>${game.rating}</td>
 </tr>
  `);
}

之后,所有内容都添加了,但我希望将它添加到我选择的表中的行中。 一切都完成后,我得到了这个,我不希望它像这样显示,我希望它像普通表一样在行中。 在此处输入图像描述

If your table has an ID, you can target it with document.getElementById and then use the built in append method to append the <tr> if you are using it as a javascript object. 您也可以(但我不建议这样做,因为它可用于 XSS 攻击)使用innerHTML属性,然后使用模板字符串或仅使用 + 运算符将 append 和 HTML 放在最后的表格主体上。

如评论中所述,您还可以使用 Table.insertRow() 和 Row.insertCell() 来完成此操作。 (信用:@charlietfl)

暂无
暂无

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

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