我有100篇关于Fetch API的帖子,我将它们全部放在同一页面上。我不知道如何制作每页只能显示10个帖子的页面。
多数民众赞成我的javascript代码:
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res)=>res.json())
.then((data)=>{
let output = '<h2 class="posts"></h2>';
let i=0;
data.forEach(function(thePost){
output += `
<div style="background-color: gray;margin-
right:60px;width:300px;height:350px;border-radius: 30px;display:
inline-block;overflow: hidden;" class="post" id=item${i}>
<h3 style="padding:10px;color:white;">${thePost.title}</h3>
<p style="padding:10px;color:white;">${thePost.body}</p>
</div>
`;
i++;
//if (i==3){`<br> <br>`}
});
document.getElementById('posts').innerHTML=output;
});
有很多方法可以实现这一目标。
方式1
您可以使用splice
方法拼接数组并仅获取前10个元素
data = data.splice(0, 10);
完整代码
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res)=>res.json())
.then((data)=>{
let output = '<h2 class="posts"></h2>';
let i=0;
data = data.splice(0, 10);
data.forEach(function(thePost){
output += `
<div style="background-color: gray;margin-
right:60px;width:300px;height:350px;border-radius: 30px;display:
inline-block;overflow: hidden;" class="post" id=item${i}>
<h3 style="padding:10px;color:white;">${thePost.title}</h3>
<p style="padding:10px;color:white;">${thePost.body}</p>
</div>
`;
i++;
//if (i==3){`<br> <br>`}
});
document.getElementById('posts').innerHTML=output;
});
方式2:
你可以使用jsonplaceholder提供的分页,它允许你在给定的n
上获得唯一的page
帖子。
为此,您可以向您的请求添加一些查询字符串参数,如下所示:
https://jsonplaceholder.typicode.com/posts?_page=0&_limit=10
完整代码
fetch('https://jsonplaceholder.typicode.com/posts?_page=0&_limit=10')
.then((res)=>res.json())
.then((data)=>{
let output = '<h2 class="posts"></h2>';
let i=0;
data.forEach(function(thePost){
output += `
<div style="background-color: gray;margin-
right:60px;width:300px;height:350px;border-radius: 30px;display:
inline-block;overflow: hidden;" class="post" id=item${i}>
<h3 style="padding:10px;color:white;">${thePost.title}</h3>
<p style="padding:10px;color:white;">${thePost.body}</p>
</div>
`;
i++;
//if (i==3){`<br> <br>`}
});
document.getElementById('posts').innerHTML=output;
});