2010-06-27 49 views
4

我想知道是否有一種方法來使用Table sorter對列進行排序
這樣我就可以根據某個ID或任何東西來安排列。
alt text使用jQuery Table Sorter排序表列

所以在這裏舉例來說,如果我想,這樣的蘋果列
將是第一個,我該怎麼辦,要對錶進行排序?

+0

表分揀機沒有這個內置的,你綁到該插件?還有其他人會這樣做,雖然沒有我能想到的輕量級。 – 2010-06-27 14:19:18

回答

1

演示:http://jsfiddle.net/fKMqD/

代碼:

var rows = $('tr'); 

rows.eq(0).find('td').sort(function(a, b){ 

    return $.text([a]) > $.text([b]) ? 1: -1; 

}).each(function(newIndex){ 

    var originalIndex = $(this).index(); 

    rows.each(function(){ 
     var td = $(this).find('td'); 
     if (originalIndex !== newIndex) 
      td.eq(originalIndex).insertAfter(td.eq(newIndex)); 
    }); 

}); 

無插件必要的。

+0

+1 ...小巧簡潔的作品! – opatut 2010-09-08 22:27:50

1

還有的jQuery插件稱爲數據表,它是非常容易使用最喜歡的插件和不上了所有的額外的工作飛你想要的一切。

http://www.datatables.net/

檢查出來。

+0

+1插件! – opatut 2010-09-08 22:29:09

0

我得到它的工作正是如此

<html> 
    <head> 
    <script type="text/javascript" src="http://www.google.com/jsapi"></script> 
    <script type="text/javascript"> 
     google.load("jquery", "1"); 
    </script> 
    <script> 
     $(function() { 
     // Figure out the new column order. 
     var isWas = {}; 
     $("tr").eq(0).find("td").each(function(index) { 
      $(this).attr("was", index); 
     }).sort(function(left, right) { 
      // Change this line to change how you sort. 
      return $(left).text() > $(right).text() ? 1 : -1; 
     }).each(function(index) { 
      isWas[index] = $(this).attr("was"); 
     }); 

     // Reorder the columns in every row. 
     $("tr").each(function() { 
      var tr = $(this); 
      var tds = tr.find("td"); 
      var newOrder = []; 
      for (var is = 0; is < tds.length; is++) { 
      newOrder.push(tds.eq(isWas[is])); 
      } 
      for (var is = 0; is < tds.length; is++) { 
      tr.append(newOrder[is]); 
      } 
     }); 
     }); 
    </script> 
    </head> 
    <body> 
    <table> 
     <tr><td>Potato</td><td>Tomato</td><td>Apple</td></tr> 
     <tr><td>20g</td><td>10gr</td><td>40gr</td></tr> 
    </table> 
    </body> 
</html>