【问题标题】:How to filter only the top rows of records with nearly similar values in a specific column?如何仅过滤特定列中具有几乎相似值的记录的顶行?
【发布时间】:2019-09-24 14:41:38
【问题描述】:
假设我们有一个包含 1000 行的 DataTable。 Col_1 的值由两个数字组成。前五条记录如下:
Col_1 Col_2
10-01 Alex
10-02 John
10-04 Sara
20-07 David
20-09 Will
. .
. .
. .
如何创建一个过滤器,只显示 Col_1 中第一部分值相同的行的顶行?过滤后的结果一定是这样的:
Col_1 Col_2
10-01 Alex
20-07 David
【问题讨论】:
标签:
jquery
html
filter
datatable
【解决方案1】:
您好,基于 datatable.net 文档中的这个示例 filtering with ranges,这是我的方法:
$(document).ready(function() {
var table = $('#example').DataTable();
let ranges = [],
reset = true;
$.fn.dataTableExt.afnFiltering.push(
function( settings, data, dataIndex ) {
if(settings.nTable.id == 'example' && reset == false ){//filter only the example table
var range = data[0] , // use data de 1 column
value = range.substr(0, range.indexOf('-')),//get the value
coincidence = false;//set a flag for coincidences
if(ranges.length == 0 ){//if array length is zero push the first element
ranges.push(value);
return true;
}else if(!ranges.includes(value)){//if not search inside the array
ranges.push(value);
coincidence = true;
}
return coincidence;
}else{
return true;
}
});
$('#btnTop').on('click', function(e) {//reset the ranges on each click
e.preventDefault();
ranges = [];
reset = false;
table.draw();
});
$('#example').on( 'order.dt', function () {//when ordening disable the filter
ranges = [];
reset = true;
table.order();
} );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table border="0" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>Get top records:</td>
<td><input type="button" id="btnTop" name="btnTop" value="Get top records"></td>
</tr>
</tbody></table>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>data</th>
<th>name</th>
</tr>
</thead>
<tbody>
<tr>
<td>10-01</td>
<td>Alex</td>
</tr>
<tr>
<td>10-02</td>
<td>Maria</td>
</tr>
<tr>
<td>10-03</td>
<td>John</td>
</tr>
<tr>
<td>10-05</td>
<td>Mikasa</td>
</tr>
<tr>
<td>20-07</td>
<td>David</td>
</tr>
<tr>
<td>20-08</td>
<td>Andreina</td>
</tr>
<tr>
<td>20-09</td>
<td>Annie</td>
</tr>
<tr>
<td>30-00</td>
<td>Svetlana</td>
</tr>
<tr>
<td>30-01</td>
<td>Harry</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>data</th>
<th>name</th>
</tr>
</tfoot>
</table>
注意:要重置表格,您可以订购 dataTable。
希望对你有帮助