javascript - HTML5/Javascript 数据表顺序/列排序
问题描述
我目前正在使用来自http://datatables.net的数据表。我有许多包含“未知”数据的列(即无法预设内容类型)
在使用数据表之前,这只是一个标准的简单表,其中使用 ASP.NET/C#/LINQ orderby(序数排序)在服务器端完成排序,这几乎适用于任何情况。
现在,对于数据表,排序大多是错误的。特别是数字以及字符串和数字的混合是错误的。
我的错误案例:
- 空字符串总是排在第一位,我希望它们排在最后。不过可以忍受这个。
- 数字/货币应正确排序。目前下单是这样的 500,12 400,00 1.123,00 223.441,00
我对这个数据表/JavaScript 世界还很陌生。对于错误情况,我已经添加了我能想到的所有插件,并且我已经对它们进行了测试,但没有成功地让列表正确排序。
我认为我想要的排序是有序的(如 ASCII 二进制),如果我能理解如何在 JS 中执行以下操作,我可以通过实现自己的排序函数来生活:
int c = String.Compare(a, b, StringComparison.Ordinal);
解决方案
不久前在数据表方面遇到了类似的挑战。这是日期,格式化数字以及德语中的特殊字符。你的名字听起来像是来自斯堪的纳维亚;我想可能也与您有关...
您需要以下数据表插件来完成所有这些操作:
这一个用于日期时间排序:https : //datatables.net/plug-ins/sorting/datetime-moment 它还需要我强烈推荐的moment.js。https://momentjs.com/
这一个用于使用特殊字符(如ä、öü等)时 的国际排序。 https://datatables.net/plug-ins/sorting/intl
这一个用于格式化数字排序: https ://datatables.net/plug-ins/sorting/formatted-numbers
下面的示例是关于根据用户语言自动检测各个字段的。
实现示例:
所以这是关于格式化数字的。英文格式为 1,000,000.99。德语格式为 1.000.000,99。它还负责处理空字段。
//sorting of formatted numbers in English and German format
$.extend( $.fn.dataTable.ext.type.order, {
"formatted-num-pre": function ( a ) {
if (lang == 'de') {
a = a.toString().replace( /[\.]/g, "" );
a = a.toString().replace( /[\,]/g, "." );
} else {
a = a.toString().replace( /[\,]/g, "" );
}
a = a.toString().replace( /[^\d.-]/g, "" );
a = parseFloat(a);
if ( ! isNaN(a) ) {
return a;
} else {
//14 digit negative number to make sure empty cells always stay at the bottom / top
return -99999999999999;
}
},
"formatted-num-asc": function ( a, b ) {
return a - b;
},
"formatted-num-desc": function ( a, b ) {
return b - a;
}
} );
这是关于国际排序的:
//sorting:
//Use the phonebook variant of the German sort order,
//which expands umlauted vowels to character pairs: ä → ae, ö → oe, ü → ue.
if (lang === 'de') {
$.fn.dataTable.ext.order.intl("de-DE-u-co-phonebk");
} else {
$.fn.dataTable.ext.order.intl("en-GB");
}
最后是关于日期排序:
//should be positioned after the number formatting to make sure
//date columns don't accidentally are assigned formatted-num
//set parms for date sorting using moment.js
$.fn.dataTable.moment( 'L', momentLocale );
在我的示例中,变量 momentLocale 是“de”或“en-gb”。相应的日期格式为 10.11.2018(德语)或 10/11/2018(英国英语)。(与美国格式的 11/10/2018 不同,我认为它要求 momentLocale 为“en”)。
推荐阅读
- python - 在 Python 中使用 groupby 计算行之间的差异百分比
- r - Rmd 加载 png 但无法将其编织到仪表板
- string - 为什么不能将字符串文字分配给 String 类型的变量
- firebase - 使用 Firebase 用户界面进行 Google 登录
- html - 如何本地化使用 URL 调用的本地 HTML 文件?
- sql - SQL 帮助:选择案例?
- jdbc - Flink、Kafka 和 JDBC 接收器
- python - 如何将其转换为更多(更快!)Pythonic 代码?
- javascript - 调用函数时,如何在另一行下显示一行?
- parsing - 如何单元和/或集成测试解析器?