phoenix.sky 前端工程师  05月23日
关于一个分页功能,没有思路了,想请教。
参考网上代码实现一个基本的分页功能,没有完全实现,没有更好的思路了,在这里请教大家。
1:目前显示所有页数,应该一次只显示[1,2,3,4,5] [6,7,8,9,10] [11,12,13,14,15] 这样的分页;
2:JS 哪些部分该改进?

谢谢!
下面是全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Go Coding!</title>
<style>
* {
margin: 0;
padding: 0;
border: none;
list-style: none;
text-decoration: none;
font-size: 12px;
}

body {
padding: 20px;
}

.title {
font-size: 16px;
color: #f80;
}

.list>li {
padding: 6px;
border-bottom: 1px solid #eee;
}

.pagination {
padding: 4px;
}

.pagination a {
display: inline-block;
padding: 4px;
margin: 0 4px 0 0;
color: #00c;
}
</style>
</head>
<body>
<ul class="list"></ul>
<section class="pagination"></section>
<script>
let data = {
"list": [
{ "id": 1, "title": 2001 },
{ "id": 2, "title": 2002 },
{ "id": 3, "title": 2003 },
{ "id": 4, "title": 2004 },
{ "id": 5, "title": 2005 },
{ "id": 6, "title": 2006 },
{ "id": 7, "title": 2007 },
{ "id": 8, "title": 2008 },
{ "id": 9, "title": 2009 },
{ "id": 10, "title": 2010 },
{ "id": 11, "title": 2011 },
{ "id": 12, "title": 2012 },
{ "id": 13, "title": 2013 },
{ "id": 14, "title": 2014 },
{ "id": 15, "title": 2015 },
{ "id": 16, "title": 2016 },
]
}

let list = data.list;
console.log(`list-length: ${list.length}`);

pagination({
"current-page": 1,
"page-size": 5,
});

function pagination(par) {
let listBox = document.querySelector(".list");
let num = data.list.length;
let totalPage = 0;
let pageSize = par["page-size"];
let currentPage = par["current-page"];

if (num / pageSize > parseInt(num / pageSize)) {
totalPage = parseInt(num / pageSize) + 1;
} else {
totalPage = parseInt(num / pageSize);
}

let sliceStart = (currentPage - 1) * pageSize;
let sliceEnd = currentPage * pageSize;
sliceEnd = sliceEnd > num ? num : sliceEnd;

let dataSlice = data.list.slice(sliceStart, sliceEnd);
let listText = "";
for (let item of dataSlice) {
listText += `
<li><h5 class="title">${item.id} - ${item.title}</h5></li>
`;
}
listBox.innerHTML = listText;

let htmlText = "";
if (currentPage > 1) {
htmlText += `
<a href="#" onClick="pagination({'current-page': ${currentPage - 1}, 'page-size': ${pageSize}})">
上一页
</a>
`;
}

for (let i = 1; i < totalPage + 1; i++) {
htmlText += `
<a href="#" onClick="pagination({'current-page': ${i}, 'page-size': ${pageSize}})">
${i}
</a>
`;
}

if (currentPage < totalPage) {
htmlText += `
<a href="#" onClick="pagination({'current-page': ${currentPage + 1}, 'page-size': ${pageSize}})">
下一页
</a>
`;
}

let pagination = document.querySelector(".pagination");
pagination.innerHTML = htmlText;
}
</script>
</body>
</html>
...全文
1207 点赞 收藏 12
写回复
12 条回复

还没有回复,快来抢沙发~

发动态
发帖子
JavaScript
创建于2007-09-28

5.1w+

社区成员

22.3w+

社区内容

Web 开发 JavaScript
社区公告
暂无公告