【问题标题】:Tablesorter sorting comma separated number columns incorrectlyTablesorter 不正确地对逗号分隔的数字列进行排序
【发布时间】:2017-10-09 19:55:40
【问题描述】:

第一次使用 jQuery:

我正在使用 tablesorter 对我的表格进行排序。它在排序数字时表现得很奇怪。这是一个如何按降序排序的示例:

这是一个如何按升序排序的示例

我尝试了一些方法,例如将类“{sorter: 'digit'}”添加到元素并添加left padding,但不知道为什么会这样。项目中的另一个表与 tablesorter 完美配合。

我的代码如下:

 $('#timeSeriesTable' + this.chartId).tablesorter({
    widgets: ["filter", "zebra"],
    widgetOptions: {
        // if true, a filter will be added to the top of each table column;
        // disabled by using -> headers: { 1: { filter: false } } OR add class="filter-false"
        // if you set this to false, make sure you perform a search using the second method below
        filter_columnFilters: true,

        // Hide filter boxes by default.
        filter_hideFilters: true,

        // Set this option to false to make the searches case sensitive
        filter_ignoreCase: true,

        // if true, search column content while the user types (with a delay)
        filter_liveSearch: true,

        // Use the $.tablesorter.storage utility to save the most recent filters (default setting is false)
        filter_saveFilters: false,

        // Delay in milliseconds before the filter widget starts searching; This option prevents searching for
        // every character while typing and should make searching large tables faster.
        filter_searchDelay: 300,

        // Applies style to columns
        zebra: ["normal-row", "alt-row"]
    },
    sortList: this.sortingList
});

感谢您的帮助。

更新:我确实发现排序基本上忽略了逗号后的任何数字。我看到了类似的问题here 并尝试添加自定义解析器,但它似乎仍然不起作用。

采取的步骤: 1.添加自定义解析器

$.tablesorter.addParser({
        id: "humanReadableNumber",
        is: function (s) {
          return /^[\d,]+$/.test(s);
        }, format: function (s) {
          return s.replace(/,/g, ''); 
        }, type: "numeric"
    });  
  1. 告诉头部使用这个解析器:

    $("#timeSeriesTable0").tablesorter({headers: {1: {sorter: 'humanReadableNumber'}}});

还是不行。我在这里遗漏了什么吗?

按升序排序的列示例,这清楚地表明正在对每个数字中逗号之前的数字进行排序:

【问题讨论】:

  • 您可能需要custom parser
  • 您能否分享一个正在使用的 HTML 示例。我认为问题在于解析器试图同时处理来自同一单元格的123+123%;您可能需要在解析器中使用.split(" "),或使用textExtraction method
  • 嗨 Mottie,我认为它正在做的是在遇到第一个逗号后剪切数字。我将添加另一个排序列的屏幕截图以显示问题..
  • 修改this demo显示问题会更好。

标签: jquery sorting tablesorter


【解决方案1】:

回答这个问题以防它帮助其他人:

我最终添加了一个解析器来处理逗号分隔的数字,然后将它作为一个类添加到 <td> 元素中。

自定义解析器代码:

  $.tablesorter.addParser({
        id: "commaSeparatedNumber",
        is: function (s) {
            return /^[0-9]?[0-9,\.]*$/.test(s);
        },
        format: function (s) {
            return $.tablesorter.formatFloat(s.replace(/,/g, ''));
        },
        type: "numeric"
  });

这是将上述解析器添加到我的<td> 元素的代码:

 td.addClass("sorter-commaSeparatedNumber");

【讨论】:

    猜你喜欢
    • 2020-03-14
    • 1970-01-01
    • 2017-07-17
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多