我正在使用datatables插件来显示数据。第一列数字之间有“-”。当我使用以下代码
$('#table').DataTable({
dom:'Brt',
columnDefs:[{targets:'_all',type:'num-fmt'}]
});
表格显示如下
我要按以下顺序显示
无论如何,我们可以以相同的格式显示数据,但通过不考虑'-'进行排序
答案 0 :(得分:1)
您可以基于两个数字的数值为您的数据类型实现自定义搜索插件:
//source data
const srcData = [
{val: '1-1'}, {val: '10-10'}, {val: '100-100'}, {val: '2-2'}, {val: '20-20'}, {val: '3-3'}, {val: '2-1'}
];
//initialize datatables
const dataTable = $('table').DataTable({
dom: 't',
order: [],
data: srcData,
columns: [{title: 'Value', data: 'val', type: 'num-num'}]
});
//compare function
const compare = (a,b) => {
([ax,ay] = a.split('-'));
([bx,by] = b.split('-'));
return parseFloat(ax) <= parseFloat(bx) && parseFloat(ay) <= parseFloat(by) ? -1 : 1
}
//custom sort plugin for type 'num-num'
Object.assign($.fn.DataTable.ext.oSort, {
'num-num-asc': (a,b) => compare(a,b),
'num-num-desc': (a,b) => compare(a,b)*(-1),
});
<!doctype html><html><head><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="application/javascript" 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"></head><body><table></table></body></html>