2

我使用 api 获取一些数据并希望使用它们并使用纯 JavaScript 在我的 HTML 页面上显示它们。我当前的 HTML:

<button onclick="load()">Load data</button>
<div id="main"></div>

我预期的使用 API 数据的结构:

<div id="main">
 <div class="wrapper">
   <img src="link will come from API" class="img-class">
   <h6 class="title"></h6>
 </div>
<div class="wrapper">
   <img src="link will come from API" class="img-class">
   <h6 class="title"></h6>
 </div>
<div class="wrapper">
   <img src="link will come from API" class="img-class">
   <h6 class="title"></h6>
 </div>
<div class="wrapper">
   <img src="link will come from API" class="img-class">
   <h6 class="title"></h6>
 </div>
.
.
.
.
.
....
</div>

这是我的js:

function load(){
  fetch("https://jsonplaceholder.typicode.com/photos")
    .then(function(response){
    return response.json()
  })
    .then((response)=>{
    var counter=0;
    for (var data of response) 
    {
      if(counter == 99){
        break;
        alert("end");
      }else{
        var wrapper = document.createElement('div');
        var img = document.createElement('img');
        img.src = data.url;
        img.setAttribute("class","img-class");
        document.getElementById('main').appendChild(img);
        document.getElementById('main').appendChild(img);
        counter++; 
      }
    }
  })
}

我能够加载图像,但现在我想制作一个适当的结构。这是工作 copen链接

4

2 回答 2

1

只需附加imgwrapper

wrapper.appendChild(img)

然后附加wrapper到文档

document.getElementById('main').appendChild(wrapper)
于 2022-01-22T02:33:21.787 回答
0

您可以创建每个元素,设置属性,然后将其附加到它的父元素。由于您没有指定 API 返回的数据结构,因此您必须更改代码以支持您的 API。在你的情况下,这样的事情应该有效。

for (var data of response) {
    const imageUrl = data['image'] // you'd want to change this

    const wrapperDiv = document.createElement('div');
    wrapperDiv.classList.add('wrapper');
    
    const imgElem = document.createElement('img');
    imgElem.src = imageUrl;
    imgElem.classList.add('img-class');
    wrapperDiv.appendChild(imgElem);

    // You didn't specify what you wanted 
    // to do with the title so make sure to add
    // to this part.
    const titleElem = document.createElement('h6');
    titleElem.classList.add('title');
    wrapperDiv.appendChild(titleElem);

    document.getElementById('main').appendChild(wrapperDiv);

}
于 2022-01-22T02:29:55.590 回答