2016-06-08 126 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