在JavaScript中实现分页跳转可以通过多种方式,常见的有基于数组的分页和使用数据库或后端API进行分页。以下是基于数组的简单分页跳转实现示例:
currentPage
:当前页码。pageSize
:每页显示的数据条数。totalPages
:总页数。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>分页示例</title>
<style>
.pagination {
display: flex;
justify-content: center;
margin-top: 20px;
}
.pagination button {
margin: 0 5px;
}
</style>
</head>
<body>
<ul id="dataList"></ul>
<div class="pagination" id="pagination"></div>
<script>
const data = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`); // 模拟100条数据
const pageSize = 10;
let currentPage = 1;
function renderData() {
const start = (currentPage - 1) * pageSize;
const end = start + pageSize;
const pageData = data.slice(start, end);
const dataList = document.getElementById('dataList');
dataList.innerHTML = '';
pageData.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
dataList.appendChild(li);
});
}
function renderPagination() {
const totalPages = Math.ceil(data.length / pageSize);
const pagination = document.getElementById('pagination');
pagination.innerHTML = '';
for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.textContent = i;
if (i === currentPage) button.disabled = true;
button.addEventListener('click', () => {
currentPage = i;
renderData();
renderPagination();
});
pagination.appendChild(button);
}
}
renderData();
renderPagination();
</script>
</body>
</html>
currentPage
和pageSize
的正确性。通过以上方法,可以实现一个简单有效的分页跳转功能。如果数据量较大或需要更复杂的分页逻辑,建议结合后端API进行优化。
领取专属 10元无门槛券
手把手带您无忧上云