我有一些代码可以在 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 来做到这一点?