2011-09-27 59 views
3

我正在使用jQuery Tablesorter來對錶格排序。我的一個列如下:如何使用jQuery Tablesorter對包含兩個div的列進行排序?

<td> 
    <div> 
     <span class="green">Yes</span> <a href="##">(unverify)</a> 
    </div> 
    <div class="hidden"> 
     <span class="red">No<>/a> <a href="##">(verify)</a> 
    </div> 
</td> 

換句話說,有兩個div,一個顯示在綠色的鏈接,以及其他顯示沒有在紅色的鏈接。其中一個div始終處於隱藏狀態,只要用戶點擊該鏈接,就會切換這兩個div。

jQuery Tablesorter無法在此列上排序。有沒有辦法讓它這樣做,或者我必須修改HTML才能使其運行?

回答

5

您可以使用textExtraction回調:

$(document).ready(function() { 

    // call the tablesorter plugin 
    $("table").tablesorter({ 
     // define a custom text extraction function 
     textExtraction: function(node) { 
      // check you're at the right column 
      if ($(node).find('.green').length == 1) { 
      // extract data from markup and return it 
      return $(node).find('div:not(.hidden)').find('span').text();; 
      } 
      else { 
      return $(node).text(); 
      } 
     } 
    }); 
}); 

我沒有測試過這一點,但它應該在理論工作

+0

謝謝,這個工作。對我來說,在'textExtraction'代碼是'$返回(節點).find(」 div:not(.hidden)')。find('span')。text();' –

+0

Oi,我剛剛意識到這適用於所有列的textExtraction函數。在表中我想讓其他列使用默認排序器排序,因爲這些列工作正常。 –

+0

@DanielT。,我的答案中的自定義分析器方法幾乎是相同的東西,但允許您指定哪些列應用它至。 –

0

你會想看看創建一個custom parser。它非常簡單,您只需指定如何通過將函數傳遞給格式字段來解釋單元格中的值。

0

一個通用的方法來排序任何類型的列,不管內容如何複雜: 添加'排序'屬性的,根據優先順序(這比在javascript中更容易)在服務器端填充'排序'值。

例如

<td sorter='1'> 
    <div> 
     <span class="green">Yes</span> <a href="##">(unverify)</a> 
    </div> 
    <div class="hidden"> 
     <span class="red">No<>/a> <a href="##">(verify)</a> 
    </div> 
</td> 
<td sorter='2'> 
    <div class="hidden"> > 
     <span class="green">Yes</span> <a href="##">(unverify)</a> 
    </div> 
    <div> 
     <span class="red">No<>/a> <a href="##">(verify)</a> 
    </div> 
</td> 

然後添加以下代碼在$(函數()

$("table.tablesorter").tablesorter({ 
    textExtraction: function(node){      
      return $(node).attr("sorter");     
    } 
}); 
相關問題