Javascript 使用 jquery,如何根据 TR 属性对表中的行重新排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3156851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using jquery, how do you reorder rows in a table based on a TR attribute?
提问by Chris
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.
我有一个类似于以下行的表。这些行通过 jquery 调用不时更新。使用 jquery,我将如何构建一个函数,根据 myAttribute 值对这些表行重新排序,将 myAttribute 值最高的行放在顶部,将 myAttribute 值最低的行放在底部?表中最多可以有 100 行。
<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>
回答by Kai
<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/
回答by MSC
Thanks, Kai. I have distilled the code a little while preserving clarity. Generally, you don't want to sort the theador tfooterparts. So, it may be handy to just target only the <tr>elements in the tbody(although this was not in Chris' original question):
谢谢,凯。我在保持清晰度的同时对代码进行了一些提炼。通常,您不想对thead或tfooter部分进行排序。因此,仅针对中的<tr>元素可能会很方便tbody(尽管这不在 Chris 的原始问题中):
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;

