我有一些代码可以在 jQuery 中对表格进行排序,如下所示。
$(document).ready(function() {
//grab all header rows
$('thead th').each(function(column){
$(this).addClass('sortable').click(function() {
var findSortKey = function($cell) {
return $cell.find('.sort-key').text().toUpperCase()
+ ' ' + $cell.text().toUpperCase();
};
var sortDirection = $(this).is('.sorted-asc') ? -1 : 1;
//step back up tree and get the rows with data
//for sorting
var $rows = $(this).parent().parent().parent().find('tbody tr').get();
//loop through all the rows and find
$.each($rows, function(index, row) {
row.sortKey = findSortKey($(row).children('td').eq(column));
});
//compare and sort the rows alphabetically or numerically
$rows.sort(function(a, b) {
if (a.sortKey.indexOf('-') == -1){
if (parseInt(a.sortKey) < parseInt(b.sortKey)) {
return -sortDirection;
}
if (parseInt(a.sortKey) > parseInt(b.sortKey)) {
return sortDirection;
}
} else {
if (a.sortKey < b.sortKey) {
return -sortDirection;
}
if (a.sortKey > b.sortKey) {
return sortDirection;
}
}
return 0;
});
//add the rows in the correct order to the bottom of the table
$.each($rows, function(index, row) {
$('tbody').append(row);
row.sortKey = null;
});
//identify the column sort order
$('th').removeClass('sorted-asc sorted-desc');
var $sortHead = $('th').filter(':nth-child(' + (column + 1) + ')');
sortDirection == 1 ? $sortHead.addClass('sorted-asc') : $sortHead.addClass('sorted-desc');
// identify the column to be sorted by
$('td').removeClass('sorted').filter(':nth-child(' + (column + 1) + ')').addClass('sorted');
//$('.visible td').removeClass('odd');
//zebraRows('.vi')
});
});
});
还有CSS
root {
display: block;
}
th.sortable {
color: #666;
cursor: pointer;
text-decoration: underline;
}
th.sortable:hover{color:black;}
th.sorted-asc, th.sorted-desc { color:black;
background-color: cadetblue;
}
这适用于一个表,但不适用于多个表。有什么方法可以根据嵌套表格的 div 的 ID 来执行此操作?
最佳答案
如果您想要一个预打包的解决方案,我过去使用过 sortable.js。这是链接:http://www.kryogenix.org/code/browser/sorttable/
实现起来非常容易。
关于jquery - 在 jquery 中对多个 html 表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622267/