使用jquery,如何根据TR属性重新排序表中的行? [英] Using jquery, how do you reorder rows in a table based on a TR attribute?

查看:727
本文介绍了使用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/

这篇关于使用jquery,如何根据TR属性重新排序表中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆