2016-06-08 124 views
0

我觉得这个问题已经发布好几次了,但我不能把答案放在一起。我的脚本生成一个包含div的HTML/JS网站,其中仅包含table。当函数refreshTbl被调用时,它应该重新加载div(这个工作)的内容,并按照之前的方式对表进行排序(不起作用)。表格应该再次可排序(也不起作用)。JQuery TableSorter重新加载并排序

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"); 

,并让脚本只能发送的表体(不包括序言和tbody标签)。也没有工作。

什么是正确的做法?

回答

1

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

为了解决这个问题,使用complete callback内置到jQuery​​函数中。

尝试此代码:

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(); 
    } 
    }); 
} 
+0

'$( “#TBL1”)触发器( “sorton”,[currentSort]);''后的init()'在'else'分支,和。那么它是完美的 - 感谢你的伟大答案。 – rexkogitans

+0

在'init()'函数中加入排序会更好:'$(“#tbl1”)。tablesorter({sortList:currentSort})''。并且将'currentSort'初始定义为一个空数组。 – Mottie