2014-03-29 92 views
-1

假設我有一張桌子。javascript - 按數字順序排列表格

<table><tr> 
<td>ID</td><td>Item</td></tr><tr> 
<td>1</td><td>Air</td></tr><tr> 
<td>7</td><td>Water</td></tr><tr> 
<td>3</td><td>Grass</td></tr><tr> 
<td>2</td><td>Dirt</td></tr> 
</table> 

我想根據項目的ID排列表格。這意味着我想安排這樣的表:

<table><tr> 
<td>ID</td><td>Item</td></tr><tr> 
<td>1</td><td>Air</td></tr><tr> 
<td>2</td><td>Dirt</td></tr><tr> 
<td>3</td><td>Grass</td></tr><tr> 
<td>7</td><td>Water</td></tr> 
</table> 

我該怎麼做,使用JavaScript?

回答

0

試用

<table id="myTbl"> 
    <thead> 
     <tr> 
      <th>ID</th><th>Item</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td class="sort_id">1</td><td>Air</td> 
     </tr> 
     <tr> 
      <td class="sort_id">7</td><td>Water</td> 
     </tr> 
     <tr> 
      <td class="sort_id">3</td><td>Grass</td> 
     </tr> 
     <tr> 
      <td class="sort_id">2</td><td>Dirt</td> 
     </tr> 
    </tbody> 
</table> 

<script> 
    $(document).ready(function() { 
     var rows = $('#myTbl > tbody').children('tr').get(); 
     rows.sort(function(a, b) { 
      var anum = parseInt($(a).find(".sort_id").text(), 10); 
      var bnum = parseInt($(b).find(".sort_id").text(), 10); 
      return anum - bnum; 
     }); 
     for (var i = 0; i < rows.length; i++) { 
      $('#myTbl > tbody').append(rows[i]); 
     } 
    }); 

</script>