使用 Fetch() 如何将 a 附加到现有元素 ID?

问题描述 投票:0回答:1
javascript html json fetch-api
1个回答
0
投票

一旦获得响应,您可以使用

map
数组方法将
d.data.children
数组转换为
img
元素数组,其中每个元素都将
src
作为来自其 data.url 的值。

// API for get requests
let fetchRes = fetch('https://www.reddit.com/r/meme/top.json');
fetchRes
  .then(res => res.json())
  .then(d => {
    const images = d.data.children.map(c => {
      const img = document.createElement('img');
      img.src = c.data.url;
      return img;
    });
    document.getElementById('container').append(...images);
  });
<body>
  <h1>Place Holder</h1>
  <p id="container"></p>
</body>

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.