我用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++;
}
}
})
}
我本来可以加载图像,但现在我想制作一个合适的结构。这是正在工作的哥本哈根链接。
您可以创建每个元素,设置属性,然后将其附加到其父元素。由于您没有指定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);
}
只需将img
附加到wrapper
wrapper.appendChild(img)
然后将CCD_ 3附加到文档
document.getElementById('main').appendChild(wrapper)