这是我的代码示例 -- 它使用了
<input>
和
<select>
,但如果您想要做些不同的事情,您应该可以很容易地适应它。在
datatables.net
提供的示例中,他们在页脚中使用搜索字段(我个人不喜欢),所以我的示例是在页眉中使用它们。首先,在您的
<thead>
中需要
两行--
确保您的过滤器行是第一行,而您的实际标题是第二行。
演示DEMO
<table class="table">
<thead>
<tr class="filter-row">
<th class="actions">
</th>
<th class="searchable datatables-dropdown">
<select name="FormName">
<option>Form1</option>
<option>Form2</option>
</select>
</th>
<th class="display-order">
</th>
<th class="searchable">
Label Text
</th>
<th class="searchable">
View Roles
</th>
<th class="searchable">
Edit Roles
</th>
<th class="searchable">
Delete Roles
</th>
<th class="searchable">
Add Roles
</th>
<th class="searchable">
Field Type
</th>
<th class="searchable">
Note Field
</th>
<th class="searchable">
Note Required
</th>
<th class="searchable">
Default
</th>
<th class="searchable">
Reason List Group
</th>
<th class="searchable">
Reason Required
</th>
</tr>
<tr>
<th class="actions">
Actions
</th>
<th>
Form Name
</th>
<th>
Display Order
</th>
<th>
Label Text
</th>
<th>
View Roles
</th>
<th>
Edit Roles
</th>
<th>
Delete Roles
</th>
<th>
Add Roles
</th>
<th>
Field Type
</th>
<th>
Note Field
</th>
<th>
Note Required
</th>
<th>
Note Default
</th>
<th>
Reason List Group
</th>
<th>
Reason Required
</th>
</tr>
</thead>
<tfoot>
</tfoot>
<tbody>
</tbody>
</table>
然后,在你的JavaScript中,你可以将筛选行从普通文本转换为像这样的<input>
元素:
$(function () {
$('.table thead tr:first th.searchable:not(.datatables-dropdown)').each(function () {
var title = $(this).text().trim();
$(this).css({ "padding": "5px" });
$(this).html('<input type="text" placeholder="Search ' + title + '" style="width: 115px;" />');
});
var table = $(".table").DataTable({
});
ApplySearchFieldsToDatatable(table);
});
function ApplySearchFieldsToDatatable (table) {
table.columns().every(function () {
var column = this,
header = $(column.header()),
searchHeader = header.parent().prev(),
currentColumn = searchHeader.children(":eq(" + header.index() + ")");
$('select', currentColumn).off("change");
$('input', currentColumn).off("input").off("propertychange");
$('select', currentColumn).on('change', function () {
if (column.search() !== this.value) {
column.search(this.value).draw();
}
});
$('input', currentColumn).on('input propertychange', function () {
if (column.search() !== this.value) {
column.search(this.value).draw();
}
});
if (column.search().length) {
currentColumn.find('input').val(column.search());
currentColumn.find('select').val(column.search());
}
});
}
column().search()
API即可。然后,将我的更改/输入处理程序改为按钮点击处理程序或以任何您喜欢的方式进行调整。 - mhodges