![](/img/trans.png)
[英]I am trying to create a increase in movement using shift key, but I don't know how to
[英]I am trying to create a specific html structure using javasacript dyanamically, but don't know how to do it
我使用 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链接。
您可以创建每个元素,设置属性,然后将 append 设置为它的父元素。 由于您没有指定 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);
}
只是 append img
到wrapper
wrapper.appendChild(img)
然后 append wrapper
到文件
document.getElementById('main').appendChild(wrapper)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.