↑
Main Page
Sorting with different data types
aTRs.sort(generateCompareTRs(iCol));
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
oTable.sortCol = iCol;
}
Next, code must be added to check whether the column index being passed in is the same as the last
sorted column index. If they are equal, the array should just be reversed instead of sorted:
function sortTable(sTableID, iCol) {
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i < colDataRows.length; i++) {
aTRs[i] = colDataRows[i];
}
if (oTable.sortCol == iCol) {
aTRs.reverse();
} else {
aTRs.sort(generateCompareTRs(iCol));
}
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
oTable.sortCol = iCol;
}
The best thing about this change is that it doesn’t require any changes in the HTML. So now when the
user clicks a column header once, it sorts into ascending order as always. When the user clicks the col-
umn header a second time, it is sorted in descending order. If the user clicks it a third time, the order
reverses once again, sorting in ascending order. But so far this only works with strings. What about other
data types?
Sorting with different data types
Although sorting strings is a good start, many times you may want to sort a column that contains other
data types. Because the DOM text nodes always contain string values, that means the data must be con-
verted before any sorting can be done. To do this, it’s necessary to create a conversion function.
377
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 377
Free JavaScript Editor
Ajax Editor
©
→