datatable js 按列筛选_datatable 自定义筛选
时间: 2023-07-25 09:03:29 浏览: 49
datatable 是一个非常流行的 jQuery 插件,用于在 Web 应用程序中处理大量数据。它允许您快速、轻松地创建复杂的数据表格,并提供了许多功能,如排序、分页、过滤和搜索。在 datatable 中,可以使用内置的搜索框进行全局搜索,但是如果您需要按列筛选,则需要自定义筛选器。
下面是一个简单的示例,演示如何在 datatable 中按列筛选:
```html
<!DOCTYPE html>
<html>
<head>
<title>Datatable Column Filters</title>
<!-- 引入必要的CSS和JS文件 -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>
<!-- 自定义筛选器 -->
<script type="text/javascript">
$(document).ready(function() {
$('#myTable').DataTable({
initComplete: function () {
this.api().columns().every(function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo($(column.footer()).empty())
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);
column
.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
});
</script>
</head>
<body>
<table id="myTable" class="display">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>Accountant</td>
<td>Tokyo</td>
<td>63</td>
<td>2011/07/25</td>
<td>$170,750</td>
</tr>
<!-- 省略部分内容 -->
</tbody>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</body>
</html>
```
在这个示例中,我们定义了一个 datatable,然后在 `initComplete` 回调函数中使用 `columns().every()` 方法对每一列进行循环。对于每一列,我们创建了一个下拉列表框,其中包含该列的所有唯一值。当用户选择一个值时,我们使用 `column.search()` 方法按该值过滤该列。
注意,我们将 `select` 元素添加到了 `tfoot` 元素中,这是因为我们要让它显示在表格的底部,而不是表头。这个 `tfoot` 元素是必需的,否则我们无法将筛选器添加到列中。
这只是一个简单的示例,您可以根据自己的需求对它进行修改和扩展。希望对您有所帮助!