说我有一张桌子。
<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 :(得分: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>