开发者

Using jquery, how do you reorder rows in a table based on a TR attribute?

开发者 https://www.devze.com 2023-01-05 04:20 出处:网络
I have a table with rows similar to the following. These rows get updated from time to time via jquery calls. Using jquery, how wo开发者_如何学编程uld I construct a function that reorders these table

I have a table with rows similar to the following. These rows get updated from time to time via jquery calls. Using jquery, how wo开发者_如何学编程uld 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);
});

Working Demo is http://www.jsfiddle.net/HELUq/1/


Thanks, Kai. I have distilled the code a little while preserving clarity. Generally, you don't want to sort the thead or tfooter parts. So, it may be handy to just target only the <tr> elements in the tbody (although this was not in Chris' original question):

    var tb = $('tbody');
    var rows = tb.find('tr');
    rows.sort(function(a, b) {
        var keyA = $(a).attr('myAttribute');
        var keyB = $(b).attr('myAttribute');
        return keyA - keyB;
    });
    $.each(rows, function(index, row) {
        tb.append(row);
    });

To sort in descending order, just reverse the return line as follows:

        return keyB - keyA;
0

精彩评论

暂无评论...
验证码 换一张
取 消