编写一个HTML具有表头排序递增或者递减筛选控件功能的表格
时间: 2024-03-22 17:42:46 浏览: 16
好的,以下是一个简单的例子,可以实现表头排序和筛选控件功能的表格:
```html
<!DOCTYPE html>
<html>
<head>
<title>Sortable and Filterable Table</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
th {
background-color: #4CAF50;
color: white;
cursor: pointer;
}
input[type=text] {
padding: 6px 10px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 10px;
margin-bottom: 16px;
}
</style>
</head>
<body>
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<table id="myTable">
<thead>
<tr>
<th onclick="sortTable(0)">Name</th>
<th onclick="sortTable(1)">Age</th>
<th onclick="sortTable(2)">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>25</td>
<td>USA</td>
</tr>
<tr>
<td>Mary</td>
<td>31</td>
<td>UK</td>
</tr>
<tr>
<td>Bob</td>
<td>18</td>
<td>Canada</td>
</tr>
<tr>
<td>Alice</td>
<td>22</td>
<td>Australia</td>
</tr>
<tr>
<td>David</td>
<td>28</td>
<td>France</td>
</tr>
</tbody>
</table>
<script>
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("myTable");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("td")[n];
y = rows[i + 1].getElementsByTagName("td")[n];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch= true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 1; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</body>
</html>
```
该例子包含一个带有“Search for names..”提示文本的文本框,并且使用`onkeyup`事件监听输入框的输入,然后调用`myFunction()`函数进行筛选。
当用户单击表头时,会触发`sortTable()`函数进行排序,可以根据所选列的内容按升序或降序排列。
请注意,该例子只是一个基本的示例,您可以根据您的需求进行修改和扩展。