使用破折号的Tablesorter自定义解析器

时间:2012-12-18 16:27:52

标签: javascript jquery tablesorter

我有一个整数,双打和几个短划线字符的组合,我需要用这个插件对它进行排序。

以下是我的一个数据表的外观:

5,841
-
121
-
1,102
-
-
743
-
144
9,065
-
2,230
200
6,450
209
0
1
45
54,463
162
8,222

我希望输出如下:

0
1
45
121
162
144
200
209
743 
1,102 
2,230 
5,841
6,450 
8,222
9,065
54,463
-
-
-
-
-
-

或者:

-
-
-
-
-
-
0
1
45
121
162
144
200
209
743 
1,102 
2,230 
5,841
6,450 
8,222
9,065
54,463

我已经尝试过这个解析器,不太合适:

jQuery.tablesorter.addParser({
  id: "commaDigit",
  is: function(s, table) {
    var c = table.config;
    return jQuery.tablesorter.isDigit(s.replace(/,/g, ""), c);
  },
  format: function(s) {
    return jQuery.tablesorter.formatFloat(s.replace(/,/g, ""));
  },
  type: "numeric"
});

$('#table_list').tablesorter({
        headers : { 
                0 : {sorter:'commaDigit'},
                1 : {sorter:'commaDigit'},
                2 : {sorter:'commaDigit'}
            }
    });

更新:

我不知道这是否相关,但我的数据是这样的:

<tr>
<td><span>122</span><td>
<td><span>12,2</span><td>
</tr>

2 个答案:

答案 0 :(得分:1)

如果您希望将破折号视为最大值,只需将它们设置为该值(Number.MAX_VALUE)即可。否则你可以使它为负(-Number.MAX_VALUE)。这是demo

$.tablesorter.addParser({
  id: "commaDigit",
  is: function(s, table) {
    return false; // no need to test since you're manually setting it
  },
  format: function(s) {
    return ($.trim(s) === '-') ? Number.MAX_VALUE : $.tablesorter.formatFloat(s.replace(/,/g, ""));
  },
  type: "numeric"
});

答案 1 :(得分:0)

您的脚本似乎运行良好

example jsfiddle

您可能希望检查<table>是否有<thead>部分标题,否则该插件将无效。

如果您使用的是asp.net和GridView,则必须明确将其设置为使用<thead>(请参阅:How can I use jquery tablesorter with an asp.net gridview? - Stack Overflow