jQuery Tablesorter - custom parser not working

时间:2023-01-19 19:24:19

I'm trying to write a custom parser for the jQuery plugin, Tablesorter. The idea is for it to sort the numbers in descending order on the first click.

我正在尝试为jQuery插件,Tablesorter编写自定义解析器。我们的想法是在第一次点击时按降序对数字进行排序。

However, when I sort the table, the order doesn't change. Sometimes a few rows move, but most of them stay the same. Here is the code:

但是,当我对表进行排序时,顺序不会改变。有时几行移动,但大多数都保持不变。这是代码:

$.tablesorter.addParser({
    id: 'desc',
    is: function(s) { return false },
    format: function(s) {
        return 1.0 / parseFloat( s.replace(/,/g,'') );
    },
    type: 'numeric'
});

The other parsers I've written are working fine. I tried 9999 minus the number instead of 1.0 divided by it, in case it was a problem with floats (no luck).

我写的其他解析器工作正常。我尝试了9999减去数字而不是1.0除以它,以防它是漂浮物的问题(没有运气)。

2 个解决方案

#1


2  

I found a solution. I had some empty cells in each column, which were being parsed as "NaN". Why this screwed up the ordering, I don't know (blank cells were intermittently spaced with regular numbers, there was no order to anything).

我找到了解决方案。我在每列中都有一些空单元格,它们被解析为“NaN”。为什么这搞砸了订单,我不知道(空白单元格间歇地用常规数字间隔,没有任何顺序)。

In short, this code works for the format function:

简而言之,此代码适用于格式化函数:

 format: function(s) {
  if ( s == '' )
   return 0;  
  return -parseInt( s.replace(/,/g,'') );
 }

#2


0  

To sort something in reverse numeric order, to me the natural way to go is to multiply it by -1, rather than the methods you've tried.

要以反向数字顺序对某些东西进行排序,对我来说,自然的方法是将它乘以-1,而不是你尝试过的方法。

As to the parser itself, the only difference I notice is that you are returning an actual number, whereas the parser example at the Tablesorter site returns a string. Perhaps converting the value back to string before returning it would work?

至于解析器本身,我注意到的唯一区别是你返回一个实际的数字,而Tablesorter站点的解析器示例返回一个字符串。也许在返回它之前将值转换回字符串会有效吗?

#1


2  

I found a solution. I had some empty cells in each column, which were being parsed as "NaN". Why this screwed up the ordering, I don't know (blank cells were intermittently spaced with regular numbers, there was no order to anything).

我找到了解决方案。我在每列中都有一些空单元格,它们被解析为“NaN”。为什么这搞砸了订单,我不知道(空白单元格间歇地用常规数字间隔,没有任何顺序)。

In short, this code works for the format function:

简而言之,此代码适用于格式化函数:

 format: function(s) {
  if ( s == '' )
   return 0;  
  return -parseInt( s.replace(/,/g,'') );
 }

#2


0  

To sort something in reverse numeric order, to me the natural way to go is to multiply it by -1, rather than the methods you've tried.

要以反向数字顺序对某些东西进行排序,对我来说,自然的方法是将它乘以-1,而不是你尝试过的方法。

As to the parser itself, the only difference I notice is that you are returning an actual number, whereas the parser example at the Tablesorter site returns a string. Perhaps converting the value back to string before returning it would work?

至于解析器本身,我注意到的唯一区别是你返回一个实际的数字,而Tablesorter站点的解析器示例返回一个字符串。也许在返回它之前将值转换回字符串会有效吗?