在JavaScript中实现表格分页功能,通常涉及以下几个基础概念:
以下是一个简单的JavaScript实现表格分页的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Pagination</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
.pagination {
margin-top: 10px;
text-align: center;
}
.pagination button {
margin: 0 5px;
}
</style>
</head>
<body>
<table id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<!-- Data will be inserted here -->
</tbody>
</table>
<div class="pagination">
<!-- Pagination buttons will be inserted here -->
</div>
<script>
const data = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 },
// Add more data as needed
];
const itemsPerPage = 2;
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>
<td>${item.age}</td>
`;
tbody.appendChild(row);
});
}
function renderPagination() {
const totalPages = Math.ceil(data.length / itemsPerPage);
const paginationDiv = document.querySelector('.pagination');
paginationDiv.innerHTML = '';
for (let i = 1; i <= totalPages; i++) {
const button = document.createElement('button');
button.textContent = i;
button.addEventListener('click', () => {
currentPage = i;
renderTable(currentPage);
renderPagination();
});
if (i === currentPage) {
button.disabled = true;
}
paginationDiv.appendChild(button);
}
}
renderTable(currentPage);
renderPagination();
</script>
</body>
</html>
通过以上步骤和示例代码,你可以轻松实现一个基本的表格分页功能。根据具体需求,可以进一步扩展和优化。
没有搜到相关的文章