html表格分页代码实例
时间: 2023-09-24 18:05:40 浏览: 53
以下是一个简单的 HTML 表格分页代码实例:
```html
<!DOCTYPE html>
<html>
<head>
<title>Table Pagination Example</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
.active {
background-color: #4CAF50;
color: white;
}
.disabled {
background-color: #ddd;
color: #aaa;
cursor: not-allowed;
}
</style>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>30</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
<td>25</td>
</tr>
<tr>
<td>Bob</td>
<td>Smith</td>
<td>40</td>
</tr>
<tr>
<td>Susan</td>
<td>Johnson</td>
<td>35</td>
</tr>
<tr>
<td>David</td>
<td>Williams</td>
<td>50</td>
</tr>
<tr>
<td>Alice</td>
<td>Brown</td>
<td>45</td>
</tr>
</tbody>
</table>
<div id="pagination">
<button id="prevBtn" class="disabled">« Prev</button>
<button id="page1" class="active">1</button>
<button id="page2">2</button>
<button id="nextBtn">» Next</button>
</div>
<script>
var table = document.getElementById("myTable");
var prevBtn = document.getElementById("prevBtn");
var nextBtn = document.getElementById("nextBtn");
var page1Btn = document.getElementById("page1");
var page2Btn = document.getElementById("page2");
var rowsPerPage = 2;
var currentPage = 1;
function showPage(page) {
var rows = table.rows;
// Hide all rows
for (var i = 1; i < rows.length; i++) {
rows[i].style.display = "none";
}
// Show the rows for the current page
for (var i = (page - 1) * rowsPerPage + 1; i < page * rowsPerPage + 1 && i < rows.length; i++) {
rows[i].style.display = "table-row";
}
// Update active page button
page1Btn.classList.remove("active");
page2Btn.classList.remove("active");
if (page == 1) {
page1Btn.classList.add("active");
} else {
page2Btn.classList.add("active");
}
// Disable/enable prev and next buttons
if (page == 1) {
prevBtn.classList.add("disabled");
} else {
prevBtn.classList.remove("disabled");
}
if (page == Math.ceil(rows.length / rowsPerPage)) {
nextBtn.classList.add("disabled");
} else {
nextBtn.classList.remove("disabled");
}
// Update current page variable
currentPage = page;
}
// Show the first page on page load
showPage(1);
// Add event listeners to prev and next buttons
prevBtn.addEventListener("click", function() {
if (currentPage > 1) {
showPage(currentPage - 1);
}
});
nextBtn.addEventListener("click", function() {
if (currentPage < Math.ceil(table.rows.length / rowsPerPage)) {
showPage(currentPage + 1);
}
});
// Add event listeners to page buttons
page1Btn.addEventListener("click", function() {
showPage(1);
});
page2Btn.addEventListener("click", function() {
showPage(2);
});
</script>
</body>
</html>
```
在这个例子中,我们创建了一个包含 6 行数据的表格,每页显示 2 行。我们还添加了两个分页按钮和两个数字按钮,用于控制表格的显示。我们使用 JavaScript 动态地显示和隐藏行,并更新分页按钮的状态。