![](/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.