jQuery dataTables 自定义排序不适用于中文数字

jQuery dataTables customized sorting is not working with Chinese numbers

我已经为我的问题创建了 jsFiddle

$.extend($.fn.dataTableExt.oSort, {
    "mysort-pre":  function (s)    { return s.replace(/(<([^>]+)>)/g, ''); },
    "mysort-asc":  function (a, b) { return a.localeCompare(b); },
    "mysort-desc": function (a, b) { return b.localeCompare(a); }
});
$(function(){
    $('table').dataTable({
        order: [[ 0, "asc" ]],
        columnDefs: [ { type: "mysort", targets: 0 } ]
    });
});

简而言之,在中文中,//分别表示1/2/3

默认情况下,它排序 > > 所以我决定编写自己的排序。

数据字段中可能(不)有一些HTML标签,所以我在'-pre'函数中使用正则表达式去除它们。

至于'-asc''-desc'函数,我直接用localCompare()应该排序 > > .

但是结果和我想的不一样

原因

以下是 DataTables 源代码的摘录:

Each ordering option can be described by three properties added to
this object:

  • {type}-pre - Pre-formatting function
  • {type}-asc - Ascending order function
  • {type}-desc - Descending order function

All three can be used together, only {type}-pre or only {type}-asc and {type}-desc together. It is generally recommended that only {type}-pre is used, as this provides the optimal implementation in terms of speed, although the others are provided for compatibility with existing Javascript sort functions.

意思是{type}-asc/{type}-desc如果有{type}-pre就不会被调用

另外,Chinese (string) 排序插件已经可用,但它不会删除 HTML 标签。

解决方案

所以从技术上讲,您的排序插件应该如下所示编写,以排序和删除 HTML 标签。

$.extend($.fn.dataTableExt.oSort, {
    "mysort-asc":  function (a, b) { 
        a = a.replace(/<[^>]+>/g, '');
        b = b.replace(/<[^>]+>/g, '');
        return a.localeCompare(b, "zh-CN-u-co-stroke"); 
    },
    "mysort-desc": function (a, b) { 
        a = a.replace(/<[^>]+>/g, '');
        b = b.replace(/<[^>]+>/g, '');       
        return b.localeCompare(a, "zh-CN-u-co-stroke"); 
    }
});

演示版

请参阅 this jsFiddle 进行演示。

注释

最初localCompare产生了意想不到的结果

  • ('三').localeCompare('二') returns -1 这意味着 '三' < '二'.

当我将其更改为 ('三').localeCompare('二', "zh-CN-u-co-stroke") 时,它产生了正确的结果。