使用jquery,如何根据TR属性重新排序表中的行?

问题描述:

我有一个包含类似于以下行的表。这些行通过jquery调用不时更新。使用jquery,我将如何根据myAttribute值构造一个重新排序这些表行的函数,将最高的myAttribute值行放在顶部,将最低的myAttribute值行放在底部?表中最多可以有100行。

I have a table with rows similar to the following. These rows get updated from time to time via jquery calls. Using jquery, how would I construct a function that reorders these table rows based on the myAttribute value putting the highest myAttribute value rows at the top and the lowest myAttribute value rows at the bottom? There could be up to 100 rows in the table.

<tr id='1' class='playerRow' myAttribute=5>
      <td> One</td>
      <td> Two</td>
</tr>
<tr id='2' class='playerRow' myAttribute=6>
      <td> One</td>
      <td> Two</td>
</tr>


<table>  
<tr id='1' class='playerRow' myAttribute='1'>
      <td> One1</td>
      <td> Two1</td>
</tr>
<tr id='2' class='playerRow' myAttribute='2'>
      <td> One2</td>
      <td> Two2</td>
</tr>
</table>

JQuery

var $table=$('table');

var rows = $table.find('tr').get();
rows.sort(function(a, b) {
var keyA = $(a).attr('myAttribute');
var keyB = $(b).attr('myAttribute');
if (keyA < keyB) return 1;
if (keyA > keyB) return -1;
return 0;
});
$.each(rows, function(index, row) {
$table.children('tbody').append(row);
});

工作演示是 http://www.jsfiddle.net/HELUq/1/