我正在学习如何使用提取API,但似乎无法弄清楚为什么使用Unsplash API时只能显示1张图像。我认为这与地图有关,但我不确定。感谢我们的指导。
document.getElementById("search").addEventListener("click", () => {
const searchTerm = document.getElementById("searchBox").value;
console.log(searchTerm);
fetch(
`https://api.unsplash.com/search/photos?client_id=e72d3972ba3ff93da57a4c0be4f0b7323346c136b73794e2a01226216076655b&query=${searchTerm}`
)
.then(response => response.json())
.then(data => {
console.log(data);
console.log(data.results);
let searchResults = data.results
.map(searchResults => {
return (document.getElementById("app").innerHTML = `<img src="${
searchResults.urls.small
}">`);
})
.join("");
});
});
此处的代码沙箱:https://codesandbox.io/s/yq918mok29
默认应显示10张图像,但仅显示1张。如何映射图像并将其显示在页面上?
答案 0 :(得分:0)
您将在每次地图迭代中覆盖元素的内容,因此您只会看到最后一个。使用map构建标记,然后将其放入文档中。
类似这样的东西:
.then(data => {
let imagesMarkup = '';
data.results
.map(searchResults => {
return (imagesMarkup += `<img src="${searchResults.urls.small}">`);
}); // note that the join was removed here
document.getElementById("app").innerHTML = imagesMarkup;
});