我对JavaScript非常垃圾我想知道是否有人可以提供帮助。
我已经从API中映射了一些数据并将其显示到页面中,我还想循环遍历图像阵列中的图像,这样每张卡片都有不同的图像。
const images = ['https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature'];
function getPeople() {
const endpoint = "https://swapi.co/api/people/";
return fetch(endpoint)
.then(function(blob) {
return blob.json();
})
.then(function(data) {
return data.results;
});
}
getPeople().then(peopleObject => {
displayPerson(peopleObject)
});
function displayPerson(peopleObject) {
const people = peopleObject.map(person => {
return `
<div class="card">
<p> ${person.name} </p>
<p> ${person.height}cm </p>
<p> -- I WANT A IMAGE FROM IMAGE ARRAY HERE -- </p>
</div>
`
}).join('');
const cardContainer = document.createElement('div');
cardContainer.className += "card-container";
cardContainer.innerHTML = people;
document.body.appendChild(cardContainer);
}
答案 0 :(得分:2)
答案 1 :(得分:1)
const images = ['https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature','https://placeimg.com/200/200/tech','https://placeimg.com/200/200/animals','https://placeimg.com/200/200/nature'];
function getPeople() {
const endpoint = "https://swapi.co/api/people/";
return fetch(endpoint)
.then(function(blob) {
return blob.json();
})
.then(function(data) {
return data.results;
});
}
getPeople().then(peopleObject => {
displayPerson(peopleObject)
});
function displayPerson(peopleObject) {
const people = peopleObject.map((person, idx) => {
return `
<div class="card">
<p> ${person.name} </p>
<p> ${person.height}cm </p>
<p> <img src = "${images[idx % images.length]}"/></p>
</div>
`
}).join('');
const cardContainer = document.createElement('div');
cardContainer.className += "card-container";
cardContainer.innerHTML = people;
document.body.appendChild(cardContainer);
}