jQuery DataTables - sort numbers only

。_饼干妹妹 提交于 2019-12-08 04:15:59

问题


Using 1.10.1 and the new data-sort html5 attributes I want to ignore certain cells from the sort order.

My column is mixed with number and text values. Example:

<tr><td data-sort="100.50">100.50 USD</td></tr>
<tr><td data-sort="">Text</td></tr>
<tr><td data-sort="50.00">50.00 USD</td></tr>

When sorting on this column I want the text cells to be ignored. So descending order would be 100,50,Text. Ascending order would be 50,100,Text.

Can I accomplish this with the data-sort attributes only or is there another way?


回答1:


I am afraid this cannot be done with data-sort or data-order alone. DataTables will try to sort ascending / descending no matter what, and what you really need is actually two different sorting values for the plain text fields, making them either the highest or the lowest value.

However, thought you maybe could use a custom sorting plug-in for this instead? See the following plugin, that extracts any number from the column, or if a number is not present, setting the sorting value to either Number.NEGATIVE_INFINITY (sorting descending) or Number.POSITIVE_INFINITY (sorting ascending) so plain text columns always are pushed to the bottom :

function sortNumbersIgnoreText(a, b, high) {
    var reg = /[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?/;    
    a = a.match(reg);
    a = a !== null ? parseFloat(a[0]) : high;
    b = b.match(reg);
    b = b !== null ? parseFloat(b[0]) : high;
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));    
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "sort-numbers-ignore-text-asc": function (a, b) {
        return sortNumbersIgnoreText(a, b, Number.POSITIVE_INFINITY);
    },
    "sort-numbers-ignore-text-desc": function (a, b) {
        return sortNumbersIgnoreText(a, b, Number.NEGATIVE_INFINITY) * -1;
    }
});

Updated. The code is cleaned up, and the plugin now sorts any kind of number, that is

  • Integers, like 123
  • Decimal numbers, like 123.45
  • Negative and positive numbers, like -123.00, +123
  • Scientific numbers, like 12.3e+10
  • Illegal numbers, like 012345

see demo -> http://jsfiddle.net/6qmkY/



来源:https://stackoverflow.com/questions/24761459/jquery-datatables-sort-numbers-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!