在Datatable jQuery中使用负值和正值排序

时间:2015-08-03 10:02:20

标签: sorting datatables datatables-1.10 columnsorting

我需要为包含正数和负数的特定列添加排序功能。

默认情况下,排序按预期工作。但就我而言,我只需要对正值进行排序。

列:百分比

值: -1%16%2%12%0%

预期输出 升序:2%12%16%0%-1%

降序:16%12%2%0%-1%

任何想法如何进行这样的排序?

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% == -1
  2. 排序时
    • 在递增返回Number.POSITIVE_INFINITY时,如果值 如果值,则在降序返回Number.NEGATIVE_INFINITY
  3. 当您对列进行排序时,只包含值> 0。