2010-06-01 52 views
0

讓自己陷入一個有趣的情況:頁面有三個表格。使用sortEnd,任何時候你排序一個表,它排序其他三個。但是,由於我將sortEnd綁定到執行排序的函數,所以您會遇到無限循環的排序/求助。它看起來像:jQuery無限循環w/tablesorter

$("table.tablesorter").tablesorter({widgets: ['zebra']}).bind("sortEnd", function() { 
    $(this).find("th.headerSortDown,.headerSortUp").each(function(i) { 
     index = $(this).attr("cellIndex"); 
     order = ($(this).is(".headerSortDown")) ? 1 : 0; 
     $("table.tablesorter").tablesorter({sortList: [[index,order]]}); 
    }); 
}); 

有關如何清理的提示?

基於從Nick Craver下面的反饋,下面的代碼似乎運作良好:

$("table.tablesorter").tablesorter({widgets: ['zebra']}).bind("sortEnd", function() { 
    var current = $(this); 
    if (current.data("sorting")) { 
     current.data("sorting", false); 
     return false; 
    } 
    $(this).find("th.headerSortDown,.headerSortUp").each(function(i) { 
     index = $(this).attr("cellIndex"); 
     order = ($(this).is(".headerSortDown")) ? 1 : 0; 
     $("table.tablesorter").not(current).data("sorting", true).trigger("sorton", [[[index,order]]]); 
    }); 
}); 

回答

0

您可以使用.data()「標記」的其他表,告訴他們不要在當前排序後執行這個處理程序,像這樣:

$("table.tablesorter").tablesorter({widgets: ['zebra']}).bind("sortEnd", function() { 
    if($(this).data("sorting")) { 
    $(this).data("sorting", false); 
    return; 
    } 
    var current = this; 
    $(this).find("th.headerSortDown,.headerSortUp").each(function(i) { 
    index = $(this).attr("cellIndex"); 
    order = ($(this).is(".headerSortDown")) ? 1 : 0; 
    $("table.tablesorter").not(current).data("sorting", true).tablesorter({sortList: [[index,order]]}); 
    }); 
}); 

這在所有其他表中的數據高速緩存存儲布爾(已經過濾掉this一個從運行再次過濾與.not())。當處理程序執行時,它會檢查該值是否存在,如果是,則跳過下一個排序,但跳過觸發其他表再次排序的循環。

+0

無法正常工作 - 其他表格的鏈條會觸發所有.tablesorter表格,因此檢查當前表格並不能解決問題。 – Wells 2010-06-01 18:55:32

+0

@Wells - 更新以適應這一點以及...我無法測試這個很容易,所以讓我知道是否有任何問題。 – 2010-06-01 19:10:14

+0

您是否在頁面上嘗試了這種方法,並將這三個表歸類爲tablesorter? :) – Wells 2010-06-01 19:18:57