我有一些代碼在jQuery中排序表,如下所示。在jquery中排序多個html表
$(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來做到這一點?
你需要改變你的選擇器,不要抓住頁面上的每一個'thead th',那麼我會建議做一個命名函數或一個jQuery插件,併爲你需要的每個表調用它 – MrOBrian 2012-07-24 00:10:48