【问题标题】:How to display all JSON Fetch API content on a HTML table using JavaScript如何使用 JavaScript 在 HTML 表上显示所有 JSON Fetch API 内容
【发布时间】:2021-06-01 12:55:25
【问题描述】:

我开始学习 JavaScript,在我的 html 表上显示从 Json PlaceHolder fake API 获得的全部数据时遇到了一些困难。使用下面的代码,我只是设法显示 API 本身的最后一个元素,而不是我想要的所有元素。

有人可以帮我弄清楚我应该怎么做吗?

代码如下:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => json.forEach(tableElements)
  )

  function tableElements (element, index, arr){
    arr[index] = document.querySelector('#posts-table tbody').innerHTML = 
    `<td>${element.userId}</td>
    <td>${element.id}</td>
    <td>${element.title}</td>
    <td>${element.body}</td>`
  }

【问题讨论】:

  • 当你多次调用x.innerHTML = y;时,你一直在覆盖x的内容。只有最后一个 y 可见。您需要将表格单元格包装在 &lt;tr&gt;&lt;/tr&gt; 中,并改用 += 运算符,它将右侧的内容添加到左侧的内容中。

标签: javascript json html-table fetch


【解决方案1】:

您的代码显示一个数据,因为当循环进行时,它会在循环通过 json 时覆盖前一个数据,将操作数更改为 += 并用行 &lt;tr&gt;... &lt;/tr&gt; 包装表格列
在这里试试这个代码

fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => json.forEach(tableElements)
  )

  function tableElements (element, index, arr){
    arr[index] = document.querySelector('#posts-table tbody').innerHTML +=
    `<tr>
        <td>${element.userId}</td>
        <td>${element.id}</td>
        <td>${element.title}</td>
        <td>${element.body}</td>
    </tr>`
  }

【讨论】:

  • 哇,我明白了!有效。谢谢!!
猜你喜欢
  • 2023-03-11
  • 2023-04-09
  • 2020-06-22
  • 2010-11-28
  • 1970-01-01
  • 2015-10-03
  • 2021-01-20
  • 2021-11-01
  • 1970-01-01
相关资源
最近更新 更多