问题描述
因此,我正在尝试进行API调用以获取图像及其标题,但此后不久就变得糟透了。 我正在尝试使用forEach循环来遍历API,并找到图像的URL及其标题。然后,我将使用CSS和HTML在我的HTML页面上显示。我如何用下面的代码实现这一目标?
我的Javascript文件(需要帮助以实现/重构)
let pictures = document.getElementById("container");
function getPhoto() {}
if (pictures) {
let URL = "https://jsonplaceholder.typicode.com/albums/2/photos";
fetch(URL)
.then((data) => data.json())
.then((photos) => {
photos.forEach((photo) => {
return `<div><img src ="${photo.url}" width="200px" height="200px/></div>`;
});
document.getElementById(
"item-count"
).innerHTML = `There are ${photos.length} photo(s) being shown`;
});
}
这是我的HTML文件:
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="stylesheet" type="text/css" href="../css/signup.css">
<link rel="stylesheet" type="text/css" href="../css/home.css">
<script defer src="../js/homeScript.js"></script>
<title>Document</title>
</head>
<body>
<div class="container">
<nav class="nav-content">
<h1 class="nav-title">Shop<span>yee</span></h1>
<li class="nav-post">
<a href="/html/home.html">Home</a>
</li>
<li class="nav-post">
<a href="/html/postimage.html">Post</a>
</li>
<li class="nav-post">
<a href="/html/viewImage.html">View</a>
</li>
<li>
<a href="/html/signup.html">Sign up</a>
</li>
<li>
<a href="/html/login.html">Login In</a>
</li>
</nav>
<h1 id="item-count"></h1>
<div class="grid-container" id="container">
</div>
</div>
</body>
</html>
这是我的使用网格系统的CSS:
.grid-container{
display:grid;
grid-template-rows: repeat(4,1fr);
grid-template-columns: repeat(4,1fr);
grid-auto-rows: 1fr;
grid-auto-columns: 1fr;
gap:.25rem;
margin:4px;
width:100%
}
解决方法
我真的无法确切地知道您到底在哪里,所以如果您可以详细说明问题所在。 也用于重构: 我看到您已经打开和关闭getPhotos()函数。您可以在函数内编写提取API调用逻辑。另外,具有UI的逻辑应放在另一个函数中,并调用getPhotos()。通过使代码更具模块化并将所有内容保留在特定功能内以完成特定任务,这可能有助于管理代码。