JQuery TableSorter 重新加载和排序

JQuery TableSorter reload and sort

我想这个问题已经发过好几次了,但我不能把答案放在一起。我的脚本生成一个 HTML/JS 站点,其中包含一个 div,而该站点仅包含一个 table。当函数 refreshTbl 被调用时,它应该重新加载 div 的内容(这有效)并按照以前的方式对 table 进行排序(无效)。 table 应该再次成为 sortable(也不起作用)。

var currentSort;

$(document).ready(
function() 
{ 
    $("#tbl1").tablesorter().bind("sortEnd", function(sorter) {
        currentSort = sorter.target.config.sortList; } );
}

);

function refreshTbl()
{
    $("#divtbl1").load(window.location.pathname + "?tableonly");
    $("#tbl1").tablesorter().bind("sortEnd", function(sorter) {
        currentSort = sorter.target.config.sortList; } );
    $("#tbl1").trigger("sorton", [currentSort]);
}

我也试过了

    $("tbl1 tbody").load(window.location.pathname + "?tableonly");

并让脚本只发送 table 正文(没有序言和 tbody 标签)。也没用。

正确的做法是什么?

问题是 .load() function 是异步的。当 javascript 执行该代码时,调用 .load() 函数,然后立即执行下一条语句;但是 table 还不存在。

要解决此问题,请使用 jQuery .load() 函数中内置的 complete callback

试试这个代码:

var currentSort = [];

function init() {
  $("#tbl1")
    .tablesorter({ sortList: currentSort })
    .bind("sortEnd", function(sorter) {
      currentSort = sorter.target.config.sortList;
    });
}

$(function() 
{ 
  init(); 
});

function refreshTbl()
{
  $("#divtbl1").load(window.location.pathname + "?tableonly", function(response, status, xhr) {
    if (status === "error") {
      console.error("ERROR!", xhr.status, xhr.statusText);
    } else {
      init();
    }
  });
}