我有一個表格中的表格行排序任務。表中的數據是日期,數字,字符串等的一切的混合物等。當我們單擊表格標題時對錶格中的行進行排序
我已經經歷了很多鏈接,我發現有一些鏈接指向準備好的庫。這對我沒有用處。最後,我經歷了很多我已經用自己所有的雀斑和碎片製作出來的東西。這是數
這唯一的工作是腳本:
$(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>
這裏是一個小提琴,如果任何人想分叉它http://jsfiddle.net/jZ6zZ/ – andrewk
我在過去廣泛使用http://tablesorter.com/docs/。你檢查過它嗎?如果是這樣,它不能滿足你的需求? –
嗨@JonP,問題是它使用從它的網站「jquery.tablesorter.js」,這是不允許的。我需要編寫代碼或由我自己構建代碼。所以唯一的選擇是編輯我自己的代碼。 – teenu