在JavaScript中实现表格分页(table页)功能,通常涉及以下几个基础概念:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Pagination</title>
<style>
table { width: 100%; border-collapse: collapse; }
table, th, td { border: 1px solid black; }
.pagination { margin-top: 10px; }
.pagination button { margin-right: 5px; }
</style>
</head>
<body>
<table id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<!-- Data will be inserted here -->
</tbody>
</table>
<div class="pagination" id="pagination"></div>
<script src="script.js"></script>
</body>
</html>
const data = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
// ... more data
];
const itemsPerPage = 10;
let currentPage = 1;
function renderTable(page) {
const start = (page - 1) * itemsPerPage;
const end = start + itemsPerPage;
const paginatedData = data.slice(start, end);
const tbody = document.querySelector('#dataTable tbody');
tbody.innerHTML = '';
paginatedData.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `<td>${item.id}</td><td>${item.name}</td>`;
tbody.appendChild(row);
});
}
function renderPagination() {
const totalPages = Math.ceil(data.length / itemsPerPage);
const paginationDiv = document.getElementById('pagination');
paginationDiv.innerHTML = '';
for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.innerText = i;
button.addEventListener('click', () => {
currentPage = i;
renderTable(currentPage);
renderPagination();
});
if (i === currentPage) button.disabled = true;
paginationDiv.appendChild(button);
}
}
renderTable(currentPage);
renderPagination();
// 前端请求示例
fetch(`/api/data?page=${currentPage}&limit=${itemsPerPage}`)
.then(response => response.json())
.then(data => {
renderTable(data);
});
// 后端伪代码示例(Node.js)
app.get('/api/data', (req, res) => {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 10;
const start = (page - 1) * limit;
const end = start + limit;
const paginatedData = data.slice(start, end);
res.json(paginatedData);
});
通过上述方法,可以实现一个基本的分页功能,并根据具体需求进行优化和扩展。
领取专属 10元无门槛券
手把手带您无忧上云