2015-09-15 58 views
-1

我怎樣才能訂購像這樣的表:jQuery的表格排序一旦

Group pos 
b  2 
c  1 
b  1 
a  1 

這樣:

Group pos 
a  1 
b  1 
b  2 
c  1 

與jquery?

該表應該不是可排序

我只想對行排序一次,我想訂購兩列。

+1

重複http://stackoverflow.com/questions/664802/jquery-sorting-a-table-without-the-plugin –

+1

這是一個html表嗎?你是否限制不使用插件?什麼生成源數據? (可以在源頭應用排序,一般來說更容易)。你到目前爲止嘗試過什麼? –

回答

1

您可以使用sort()排序表

$('tbody tr').sort(function(a, b) { 
 
    var td1 = $(a).find('td'), 
 
    td2 = $(b).find('td'); 
 
    // condition for sort - compare with first column if they are equal then compare with second column 
 
    return (td1.eq(0).text() > td2.eq(0).text() || (td1.eq(0).text() == td2.eq(0).text() && td1.eq(1).text() > td2.eq(1).text())) || 0; 
 
}).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table> 
 
    <thead> 
 
    <tr> 
 
     <th> 
 
     Group</th> 
 
     <th>pos</th> 
 
     <tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td> 
 
     b 
 
     </td> 
 
     <td>2</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     c 
 
     </td> 
 
     <td>1</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     b 
 
     </td> 
 
     <td>1</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     a 
 
     </td> 
 
     <td>1</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

或者

$('tbody tr').sort(function(a, b) { 
 
    var td1 = $(a).find('td'), 
 
    td2 = $(b).find('td'); 
 
    // condition for sort - compare with first column if they are equal then compare with second column 
 
    if (td1.eq(0).text() > td2.eq(0).text() || (td1.eq(0).text() == td2.eq(0).text() && td1.eq(1).text() > td2.eq(1).text())) 
 
    return 1; 
 
    else if (td1.eq(0).text() < td2.eq(0).text() || (td1.eq(0).text() == td2.eq(0).text() && td1.eq(1).text() < td2.eq(1).text())) 
 
    return -1; 
 
    return 0; 
 
}).appendTo('table tbody');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<table> 
 
    <thead> 
 
    <tr> 
 
     <th> 
 
     Group</th> 
 
     <th>pos</th> 
 
     <tr> 
 
    </thead> 
 
    <tbody> 
 
    <tr> 
 
     <td> 
 
     b 
 
     </td> 
 
     <td>2</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     c 
 
     </td> 
 
     <td>1</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     b 
 
     </td> 
 
     <td>1</td> 
 
    </tr> 
 
    <tr> 
 
     <td> 
 
     a 
 
     </td> 
 
     <td>1</td> 
 
    </tr> 
 
    </tbody> 
 
</table>