jQuery 表排序器插件辅助"hidden"排序



我使用的是jQuery表分类器插件,我有一列包含月份和年份的名称,就像这个

April, 1975
January, 2001

我希望将此列作为日期列进行排序。据我所知,可以使用其他"隐藏"值对列进行排序,但我似乎找不到该功能的文档。有人帮忙吗?

更新

这个叉子http://mottie.github.com/tablesorter/docs/index.html桌子分拣机的正是我所需要的;将要排序的值存储在属性中的能力非常好。

只需使用textExtraction函数。在TD上设置数据排序值。如果不存在,则默认为普通文本。

$(".sort-table").tablesorter({
    textExtraction: function(node) {
        var attr = $(node).attr('data-sort-value');
        if (typeof attr !== 'undefined' && attr !== false) {
            return attr;
        }
        return $(node).text(); 
    } 
}); 

我有一个表分类器的分支,它允许您编写一个解析器,可以从表单元格中提取数据属性,并为每列分配特定的textExtraction。

$(function(){
  $.tablesorter.addParser({ 
    // set a unique id 
    id: 'myParser', 
    is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
    }, 
    format: function(s, table, cell, cellIndex) { 
      // get data attributes from $(cell).attr('data-something');
      // check specific column using cellIndex
      return $(cell).attr('data-something');
    }, 
    // set type, either numeric or text 
    type: 'text' 
  }); 
  $('table').tablesorter({ 
    headers : { 
      0 : { sorter: 'myParser' }
    }
  });
});

这现在是表分类器的一个标准功能,尽管由于某些原因没有记录。如果打开文件https://github.com/christianbach/tablesorter/blob/master/jquery.tablesorter.js看看线#307,你会看到它支持";数据排序值";属性

用法:

<td data-sort-value="42">Answer to the question</td>

这有点像黑客(好吧,这是一个完全的黑客),但如果你将列的解析器设置为"text",并用你真正想在隐藏跨度内排序的字符串预先修复你的漂亮输出,它将正确排序。

您可以使用headers选项在列上设置解析器,例如,要将第一列和第二列上的解析器设置为"text",您需要设置以下内容:

headers: {0: {sorter: 'text'}, : {sorter: 'text'}

要在日期方面做到这一点,您可以使用ISO8601日期格式,该格式按词汇排序。JS的Date对象可以通过toISOString()函数生成ISO8601日期字符串。

给定CSS:

span.hidden{
    display:none;
}

表中的示例单元格如下所示:

<td><span class="hidden">2015-04-18T23:48:33</span>19 April 2015</td>

不是世界上最漂亮的代码,但它确实有效。

我正在使用

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.29.0/js/jquery.tablesorter.min.js"></script>

使用数据文本

<td data-text="42">Answer to the question</td>

数据排序值不工作

<td data-sort-value="42">Answer to the question</td>

您需要编写自己的解析器。您的解析器可能最终看起来像:

var months = {'January':1,'February':2, ...};
$.tablesorter.addParser({
    id: 'myDate', 
    is: function(s) { return false; }, 
    format: function(s) {
        var x = s.split(', ');
        return x[1]+'-'+months[x[2]];
    },
    type: 'numeric' 
});

未经测试,但总体思路。

最新更新