Tablesorter 使用实时数据重新排序

Posted

技术标签:

【中文标题】Tablesorter 使用实时数据重新排序【英文标题】:Tablesorter re-sort with live data 【发布时间】:2013-10-27 02:02:19 【问题描述】:

我有一个 tablesorter 表,其中我有一个 TD 每 20 秒更新一次,随着数据的变化,我从数据库中提取新值,使用以下代码:

window.setInterval(function()
    $("td.odds span").each(function()
        var id=$(this).parent().attr("rel");
        $(this).load("/td.php?id="+id);
    );
,20000);

我想知道的是是否有可能在此之后重新排序表格,以防任何值发生变化(如果有的话,现在表格的顺序可能是错误的) .

我尝试添加以下代码但没有成功:

var sorting=[[11,0]]; 
$("table.formguide").trigger("sorton",[sorting]);

还有:

$("table.formguide").trigger("update");

但没有成功。任何帮助表示赞赏。

【问题讨论】:

好吧,奇怪的是我已经让它在其他列上工作,但不是我想要的。出于某种原因,当我在初始表排序中引用标题时,有问题的列是 11,但是当我使用触发器按 [[11,0]] 排序时,这实际上是之前的列。大概其中一个从零开始,另一个不...无论如何,即使我使用sorting = [[12,0]],表格也不会在此列上排序。 我推测这是因为此列包含 SPAN 和 A 标签中的数据。在原始表排序中,我使用 textExtraction 函数: textExtraction:function(node) return $(node).find("span").first().text(); 【参考方案1】:

您可以尝试使用updateCell 方法专门针对修改后的单元格,然后应用sorton 方法来使用该列。

var cell = $('table.formguide td.odds span').each(function()
    $('table.formguide').trigger('updateCell', [ this ]);
);
$('table.formguide').trigger('sorton', [ [[11,0]] ]);

或者,您可以查看我的 fork of tablesorter,它修改了 updateCell method 以包含一个使用当前排序自动恢复的标志

var last,
    // resort is true by default, but we set it to false until all cells have updated
    resort = true,
    // callback function run on the last updated cell
    callback = function() /* do something after each updateCell */ ,
    // updated cells
    $cells = $('table.formguide td.odds span'),
    len = $cells.length

$cells.each(function(i)
    last = i === len;
    // don't resort or trigger a callback until we're on the last cell
    $('table.formguide').trigger('updateCell', [ this, last ? resort : false, last ? callback : null ]);
);

【讨论】:

【参考方案2】:

改用updateAll,有一个example 使用tablesorter v2.8。

  var resort = true, // re-apply the current sort
    callback = function()
      // do something after the updateAll method has completed
    ;

  // let the plugin know that we made a update, then the plugin will
  // automatically sort the table based on the header settings
  $("table").trigger("updateAll", [ resort, callback ]);

【讨论】:

以上是关于Tablesorter 使用实时数据重新排序的主要内容,如果未能解决你的问题,请参考以下文章

大数据量实时统计排序分页查询 优化总结

jQuery插件Tablesorter错误地对日期进行排序

jQuery插件 tablesorter 表格排序 使用说明

jQuery插件 tablesorter 表格排序 使用说明

[原创]游戏中的实时排行榜实现

通过jQuery实时监听表格行数变化