如何在标题中通过多种方式对一列进行排序?

我有来自motti的tablesorter,我找不到一种简单的方法,可以从同一标题中的2个不同的热区域以多种方式对某列进行排序。 (通过“游戏名称”的一种方式和通过“百分比”的另一种方式。)
我的代码已经在游戏名称上对Game进行了排序,但是在点击百分比时它也会这样做(所以后者不是按百分比,而是按名称)。

什么是最不用的代码方式? (最好使用现有的tablesorter选项。)

表头列:

Game % 

正文栏目:

  
Alphabetic 66%

Domready代码:

  $("#games") .tablesorter({ sortList: [['.percSort',1]], textExtraction:{ 1:function(node, table, cellIndex) { return $(node).find('.name').text(); }, '.percSort':function(node, table, cellIndex) { return $(node).find('.perc').text(); } } }); 

我不能做的事情:在更多列中拆分我的相应列。 它通过您可以看到的CSS显示彩色条。

文本提取的工作方式是仅在初始化或更新表时使用。 这并不意味着在同一个单元格中对两个不同的信息块进行排序,但是可以使用它以某种方式格式化文本,然后使用textSorter选项对所需的部分进行排序( 演示 ):

 $(function () { var $cell; $('#games').tablesorter({ theme: 'blue', textExtraction: { 0: function (node, table, cellIndex) { var $n = $(node); // add semi-colon between values return $n.find('.name').text() + ';' + $n.find('.perc').text(); } }, textSorter: function (a, b) { var x = a.split(';'), y = b.split(';'), i = $cell && $cell.is('.active') ? 1 : 0; return $.tablesorter.sortNatural($.trim(x[i]), $.trim(y[i])); }, initialized: function () { $cell = $('#games').find('.percSort'); // trigger sort here because any initial sort using sortList // won't have the $cell variable defined, so it defaults to name $('#games').trigger('sorton', [ [[1,1]] ]); $cell.click(function () { // activate percentage sort $cell.addClass('active'); return false; }).closest('th').click(function () { // clicking on header outside of percSort // inactivates the percentage sort $cell.removeClass('active'); }); } }); }); 

更新:

  • 要确保未检测到列仅使用百分比解析器,请在标头中设置排序器类型:

     Game... 
  • 要使表最初按百分比排序,您需要做两件事:

    • 将“有效”类添加到单元格 66% 

    • 添加$('#games').trigger('sorton', [ [[1,1]] ]); 因为在tableorter初始化之后才定义$cell变量。 并且您之前无法定义它,因为标头在初始化期间重建。 代码添加到上面的示例中。

现有选项是不可能的,因为tablesorter只允许您设置(而不是更改)列的单个排序顺序。 但是有一个解决方法,它只是根据您单击的标题上的位置关闭和打开自定义解析器:

表头列:

 Game % 

JavaScript的:

 // Add custom table parser for percentage. $.tablesorter.addParser({ id: 'perc', format: function(s, table, cell, cellIndex) { return $(cell).find('.perc').text().slice(0, -1); }, type: 'numeric' }); // Create tablesorter and disable default sorting for column. $('#games').tablesorter({ ... }); $('#thgame').unbind(); // Create custom sorting events for column. $('#thgame').click(function(){ $('#thgame').removeClass('sorter-perc'); $('#games').trigger('updateRows'); $('#games').trigger('sorton', [ [[0,'n']] ]); }); $('.percSort').click(function(e){ $('#thgame').addClass('sorter-perc'); $('#games').trigger('updateRows'); $('#games').trigger('sorton', [ [[0,'n']] ]); e.stopPropagation() // prevent previous event from firing. });