要实现一个JavaScript表格分页,你需要理解以下几个基础概念:
以下是一个简单的表格分页实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Pagination</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<table id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<!-- Data rows will be inserted here -->
</tbody>
</table>
<div id="pagination">
<button id="prevPage">Previous</button>
<span id="pageInfo"></span>
<button id="nextPage">Next</button>
</div>
<script>
const data = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
// ... more data
];
const itemsPerPage = 10;
let currentPage = 1;
function displayData(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><td>${item.age}</td>`;
tbody.appendChild(row);
});
document.getElementById('pageInfo').textContent = `Page ${page} of ${Math.ceil(data.length / itemsPerPage)}`;
}
document.getElementById('prevPage').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
displayData(currentPage);
}
});
document.getElementById('nextPage').addEventListener('click', () => {
if (currentPage < Math.ceil(data.length / itemsPerPage)) {
currentPage++;
displayData(currentPage);
}
});
// Initialize the first page
displayData(currentPage);
</script>
</body>
</html>通过以上步骤和代码示例,你可以实现一个基本的表格分页功能。根据实际需求,还可以进一步扩展和优化。