我需要为包含正数和负数的特定列添加排序功能。
默认情况下,排序按预期工作。但就我而言,我只需要对正值进行排序。
列:百分比
值: -1%16%2%12%0%
预期输出 升序:2%12%16%0%-1%
降序:16%12%2%0%-1%
任何想法如何进行这样的排序?
答案 0 :(得分:2)
您需要创建一个自己完成的自定义排序插件。你可以这样做:
function ignoreZeroOrBelow(a, b, high) {
a = parseFloat(a);
a = a>0 ? a : high;
b = parseFloat(b);
b = b>0 ? b : high;
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"sort-positive-numbers-only-asc": function (a, b) {
return ignoreZeroOrBelow(a, b, Number.POSITIVE_INFINITY);
},
"sort-positive-numbers-only-desc": function (a, b) {
return ignoreZeroOrBelow(a, b, Number.NEGATIVE_INFINITY)*-1;
}
});
用法:
var dataTable = $('#example').dataTable({
columnDefs: [
{ type: 'sort-positive-numbers-only', targets : 0 }
],
});
演示 - &gt;的 http://jsfiddle.net/scuo0t6k/ 强>
插件背后的想法非常简单
-1%
== -1
)Number.POSITIVE_INFINITY
时,如果值Number.NEGATIVE_INFINITY
时当您对列进行排序时,只包含值> 0。