jQuery DataTables-仅对数字排序 [英] jQuery DataTables - sort numbers only

查看:125
本文介绍了jQuery DataTables-仅对数字排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用1.10.1和新的数据排序html5属性,我想忽略排序顺序中的某些单元格.

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>

在此列上排序时,我希望忽略文本单元格.因此,降序将为100,50,Text.升序为50,100,文本.

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?

推荐答案

恐怕仅凭data-sortdata-order不能做到这一点.无论如何,DataTable都将尝试按升序/降序进行排序,而您真正需要的实际上是纯文本字段的两个不同的排序值,使它们成为最大值或最小值.

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.

但是,您认为您可以为此使用自定义排序插件吗?请参阅以下插件,该插件从列中提取任何数字,或者,如果不存在数字,则将排序值设置为Number.NEGATIVE_INFINITY(降序排序)或Number.POSITIVE_INFINITY(升序排序),以便将纯文本列始终推送到底部:

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

  • 整数,例如123
  • 十进制数字,例如123.45
  • 负数和正数,例如-123.00,+ 123
  • 科学数字,例如12.3e + 10
  • 非法数字,例如012345

请参阅演示-> http://jsfiddle.net/6qmkY/

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

这篇关于jQuery DataTables-仅对数字排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆