javascript 按列对表进行排序 jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16588123/
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
Sorting tables by columns jquery
提问by Gandalf StormCrow
I wouldn't want to use plugin to sort my table such as tablesorter because it would be an overhead for desired functionality.
我不想使用插件来对我的表进行排序,例如 tablesorter,因为这将是所需功能的开销。
I want to sort my table only once when page is loaded I don't want that functionality to be available all the time.
我只想在加载页面时对我的表格进行一次排序我不希望该功能一直可用。
So imagine if I have i rows each containing k columns and k #2 is the one I want to use for this sorting so my sorting would be based on this column in descending order I want to sort their rows.
所以想象一下,如果我有 i 行,每行包含 k 列,而 k #2 是我想用于此排序的行,因此我的排序将基于此列按降序排列,我想对它们的行进行排序。
Something like this :
像这样的事情:
var $rows = $("#score-table tr");
$.each($rows, function(index, row) {
//sort table
});
回答by ?????
Well if you know which column you are sorting on you can easily sort the table using javascript's sort function
好吧,如果您知道要排序的列,则可以使用 javascript 的排序功能轻松地对表格进行排序
var $tbody = $('table tbody');
$tbody.find('tr').sort(function(a,b){
var tda = $(a).find('td:eq(1)').text(); // can replace 1 with the column you want to sort on
var tdb = $(b).find('td:eq(1)').text(); // this will sort on the second column
// if a < b return 1
return tda < tdb ? 1
// else if a > b return -1
: tda > tdb ? -1
// else they are equal - return 0
: 0;
}).appendTo($tbody);
If you want ascending you just have to reverse the >
and <
如果你想上升,你只需要反转>
和<
If they are just numbers you can just do a-b
for ascending or b-a
for descending
如果它们只是数字,你可以只做a-b
升序或b-a
降序
After the sort is complete just append it back to the body and your done
排序完成后,只需将其附加回正文即可