我有一个数据表,其中包含搜索框和列搜索。首先,在每次搜索后,基本上是在每次搜索后,每次绘制之后,我如何调用函数。然后在我的函数中,我想遍历所有匹配的记录,如果第5列有一个值,则将其添加到计数器,如果第6列(隐藏)有一个值,则将其加起来。我试图在数据表上方创建一个仪表板,该仪表板会根据过滤的结果进行更改。
我发现此内容是在搜索发生时创建函数的,但不确定是在过滤之前还是之后触发,但无法正常工作
$("#example").on('search.dt', function() {
//在这里做总结
});
如果这是正确的,我如何遍历如上所述的所有过滤结果?
答案 0 :(得分:1)
汇集了一个简短而肮脏的示例,以帮助您入门。基本上,“绘制”功能上的表格会在搜索或过滤事件中触发。在此,您可以使用{ filter : 'applied'}
运行此代码段并搜索“纽约”。然后检查控制台以查看数据和数字的行为。
Or this fiddle if you prefer...
var mytable = new Object();
var tableData = [
{name: 'Clark Kent', city: 'Metropolis', numCol: '10', numCol2: '6'},
{name: 'Bruce Wayne', city: 'New York', numCol: '', numCol2: '12'},
{name: 'Steve Rogers', city: 'New York', numCol: '30', numCol2: '10'},
{name: 'Peter Parker', city: 'New York', numCol: '44', numCol2: ''},
{name: 'Thor Odinson', city: 'Asgard', numCol: '55', numCol2: '15'}
];
mytable = $('#mytable').DataTable({
"search": {
"regex": true
},
sDom: 'lrftip',
data: tableData,
columns: [
{data: 'name', title: 'Name'},
{data: 'city', title: 'City'},
{data: 'numCol', title: 'Number'},
{data: 'numCol2', title: 'Hidden Num', visible: false}
],
columnDefs: [
{ className: "sum", "targets": [2] },
]
});
mytable.on( 'draw', function () {
console.log( 'Redraw occurred at: '+new Date().getTime() );
var myCount = 0;
var totalSum = 0;
mytable.rows( { filter : 'applied'} ).every(function (rowIdx, tableLoop, rowLoop) {
var data = this.data();
console.log('num1: ' + data.numCol + ' num2: ' + data.numCol2);
if (data.numCol !== '') {
//Add to counter
myCount += 1;
}
if (data.numCol2 !== '') {
//Sum it up
totalSum += parseInt(data.numCol2);
}
});
console.log('myCount: ' + myCount + ' totalSum: ' + totalSum);
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<div class="table-responsive">
<table id="mytable" class="table nowrap table-hover table-striped dataTable">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Number1</th>
<th>Number2</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot id="mytableFoot">
<tr>
<th>Name</th>
<th>City</th>
<th>Number1</th>
<th>Number2</th>
</tr>
</tfoot>
</table>
</div>
希望这会有所帮助。