我有下表
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="OutputTable>
<tbody id="tableData">
<tr>
<td><input type="checkbox"></td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
</tr>
<tr>
<td><input type="checkbox"></td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
<td>Sometext</td>
</tr>
</tbody>
<tfoot>
<tr id="filterRow">
<th><input type="checkbox"></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
我希望页脚中的复选框起到过滤器的作用;当它被选中时,我只希望显示所有带有复选框的行。当未选中页脚复选框时,我希望显示所有行。
我尝试了不同的方法,但我无法让它工作。感谢您的帮助!
最佳答案
有关代码和演示,请参见下面的示例。
$(document).ready(function() {
var table = $('#example').DataTable({
'ajax': 'https://api.myjson.com/bins/1us28',
'columnDefs': [
{
'targets': 0,
'className': 'dt-body-center',
'render': function(data, type, row){
if(type === 'display'){
data = '<input type="checkbox" value="' + $('<div>').text(data).html() + '">';
}
return data;
}
}
],
'order': [[1, 'asc']]
});
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input[type="checkbox"]', this.footer() ).on( 'change', function (e) {
var values = '';
if(this.checked){
$.each(table.column(0).$('input:checked'), function(index, el){
var value = $.fn.dataTable.util.escapeRegex(el.value);
values += ((values !== '') ? '|' : '') + value;
});
values = '^(' + values + ')$';
}
that.search(values, true, false).draw();
});
});
// Handle checkbox change event to exclude the row if column is being filtered
$('#example').on( 'change', 'tbody input[type="checkbox"]', function (e) {
var td = $(this).closest('td');
var col = table.cell(td).index().column;
// If column is being filtered
if(table.column(col).search() !== ''){
// Trigger change event to exclude the row
$( 'input[type="checkbox"]', table.column(col).footer()).trigger('change');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/s/dt/dt-1.10.10,se-1.1.0/datatables.min.js"></script>
<link href="https://cdn.datatables.net/s/dt/dt-1.10.10,se-1.1.0/datatables.min.css" rel="stylesheet"/>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th><input type="checkbox"></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
关于javascript - 根据复选框过滤表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508274/