2010-06-27 58 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>