初级前端工程师试卷-11 答案
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>用户评论应用</title>
<style>
/* CSS 样式 */
.post {
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>用户评论应用</h1>
<div id="postList"></div>
<script>
// JavaScript 代码
const postList = document.getElementById("postList");
// 显示加载动画
postList.innerHTML = "加载中...";
// 发送Ajax请求获取文章和评论数据
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((posts) => {
// 移除加载动画
postList.innerHTML = "";
// 遍历文章数据并显示在页面上
posts.forEach((post) => {
const postDiv = document.createElement("div");
postDiv.classList.add("post");
postDiv.innerHTML = `<h2>${post.title}</h2><p>${post.body}</p>`;
// 点击文章标题展开/折叠评论
let expanded = false;
postDiv.addEventListener("click", () => {
if (!expanded) {
expanded = true;
// 发送Ajax请求获取评论数据
fetch(
`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`
)
.then((response) => response.json())
.then((comments) => {
const commentList = document.createElement("ul");
comments.forEach((comment) => {
const commentItem = document.createElement("li");
commentItem.textContent = comment.body;
commentList.appendChild(commentItem);
});
postDiv.appendChild(commentList);
})
.catch((error) => {
console.error("获取评论数据失败:", error);
});
} else {
expanded = false;
const commentList = postDiv.querySelector("ul");
if (commentList) {
commentList.remove();
}
}
});
postList.appendChild(postDiv);
});
})
.catch((error) => {
console.error("获取文章数据失败:", error);
postList.innerHTML = "加载失败,请重试。";
});
</script>
</body>
</html>
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>博客文章列表</title>
<style>
/* CSS 样式 */
.blog {
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>博客文章列表</h1>
<div id="blogList"></div>
<script>
// JavaScript 代码
const blogList = document.getElementById("blogList");
// 显示加载动画
blogList.innerHTML = "加载中...";
// 发送Ajax请求获取博客文章数据
fetch("https://jsonplaceholder.typicode.com/posts")
.then((response) => response.json())
.then((data) => {
// 移除加载动画
blogList.innerHTML = "";
// 遍历博客文章数据并显示在页面上
data.forEach((blog) => {
const blogDiv = document.createElement("div");
blogDiv.classList.add("blog");
blogDiv.innerHTML = `<h2>${blog.title}</h2><p>${blog.body}</p>`;
// 点击标题展开/折叠文章内容
let expanded = false;
blogDiv.addEventListener("click", () => {
expanded = !expanded;
blogDiv.querySelector("p").style.display = expanded
? "block"
: "none";
});
blogList.appendChild(blogDiv);
});
})
.catch((error) => {
console.error("获取博客文章数据失败:", error);
blogList.innerHTML = "加载失败,请重试。";
});
</script>
</body>
</html>