好吧,我正在尝试使用一个简单的 API 并循环遍历我收到的所有数据并将其显示在 html 上。我偶然发现了一些简单的事情,但我不知道我在哪里犯了错误。
目前我使用
fetch
获取数据,但是当我尝试在 html
上显示该数据时,我只是获取 array
中的第一个对象,而不是所有对象。
我想获得我的 html 中所有帖子的列表。
提前致谢
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Document</title>
</head>
<body>
<div class="d-flex justify-content-center">
<div class="spinner-border" role="status" id="loading">
<span class="sr-only">Loading...</span>
</div>
</div>
<h1>List of Posts</h1>
<section id="section">
<ul id='posts'></ul>
</section>
</body>
<script>
const API_URL = `https://jsonplaceholder.typicode.com`
async function fetchPosts() {
const response = await fetch(`${API_URL}/posts`)
let data = await response.json()
// console.log(data)
if (response) {
hideloader();
}
show(data)
}
function hideloader() {
document.getElementById('loading').style.display = 'none';
}
function show(data) {
console.log(data, ' inside show')
const ul = document.getElementById('posts')
const list = document.createDocumentFragment();
let li = document.createElement('li');
let title = document.createElement('h1');
let body = document.createElement('p')
data.map(function (post) {
title.innerHTML = `${post.title}`;
body.innerHTML = `${post.body}`;
li.appendChild(title);
li.appendChild(body);
list.appendChild(li);
// console.log(list)
// console.log(li)
})
ul.appendChild(list);
}
fetchPosts()
</script>
</html>
在
show(data)
功能中,当您映射 data
时,title.innerHTML
和 body.innerHTML
会不断重新分配。
您应该在迭代中创建 list
title
和 body
元素。
function show(data) {
const ul = document.getElementById('posts');
const list = document.createDocumentFragment();
data.map(function (post) {
let li = document.createElement('li');
let title = document.createElement('h1');
let body = document.createElement('p');
title.innerHTML = `${post.title}`;
body.innerHTML = `${post.body}`;
li.appendChild(title);
li.appendChild(body);
list.appendChild(li);
});
ul.appendChild(list);
}