我的任务是对表格中的表格行进行排序。表中的数据是日期、数字、字符串等所有内容的混合。
我浏览了许多链接,发现其中一些链接指向准备好的库。这对我没有用。最后经历了很多我自己用所有的山雀和比特做的事情。仅适用于数字
这是脚本:
$(document).ready(function () {
//grab all header rows
$('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;
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');
});
});
});
这是文档的样式:
<style>
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;
}
</style>
所以下面是 HTML 部分。
<table>
<tbody>
<tr>
<th class="sortable">Name</th>
<th class="sortable">Salary</th>
<th>Extension</th>
<th>Start date</th>
<th>Start date (American)</th>
</tr>
<tr>
<td>Bloggs, Fred</td>
<td>$12000.00</td>
<td>1353</td>
<td>18/08/2003</td>
<td>08/18/2003</td>
</tr>
<tr>
<td>Turvey, Kevin</td>
<td>$191200.00</td>
<td>2342</td>
<td>02/05/1979</td>
<td>05/02/1979</td>
</tr>
<tr>
<td>Mbogo, Arnold</td>
<td>$32010.12</td>
<td>2755</td>
<td>09/08/1998</td>
<td>08/09/1998</td>
</tr>
<tr>
<td>Shakespeare, Bill</td>
<td>$122000.00</td>
<td>3211</td>
<td>12/11/1961</td>
<td>11/12/1961</td>
</tr>
<tr>
<td>Shakespeare, Hamnet</td>
<td>$9000</td>
<td>9005</td>
<td>01/01/2002</td>
<td>01/01/2002</td>
</tr>
<tr>
<td>Fitz, Marvin</td>
<td>$3300</td>
<td>5554</td>
<td>22/05/1995</td>
<td>05/22/1995</td>
</tr>
</tbody>
</table>