↑
Main Page
Modifying the sortTable() function
The
generateCompareTRs()
function takes only one argument, which is the index of the column to act
on. It returns as its function value another function that looks suspiciously like
compareTRs()
. Note
that the
iCol
argument, even though it isn’t defined within the comparison function, is used within the
comparison function. You may recognize this as a closure (discussed back in Chapter 2, “ECMAScript
Basics”). The variable
iCol
is
captured
by the comparison function and, therefore, can be used when it is
returned by
generateCompareTRs()
.
With the function defined, you can generate any comparison function necessary to sort a column:
var compareTRs = generateCompareTRs(0);
var compareTRs1 = generateCompareTRs(1);
var compareTRs2 = generateCompareTRs(2);
The first line in the previous code generates the exact same
compareTRs()
function you first defined in
the previous section. The second and third lines generate a comparison function that compares the sec-
ond and third columns, respectively. Of course, you don’t need to assign the comparison function to a
variable; it can just be passed directly into the
sort()
method:
aTRs.sort(generateCompareTRs(0));
In fact, this is how the
sortTable()
function must be modified to work with multiple columns.
Modifying the sortTable() function
Because there are multiple columns to deal with, the
sortTable()
function must now accept
another argument indicating the index of the column to sort. Then, it can pass that value into the
generateCompareTRs()
function to sort the appropriate column:
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];
}
aTRs.sort(generateCompareTRs(iCol));
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
With these two changes, it’s now possible to pass in which column to sort. Don’t forget, this change also
needs to be included on the column headers in the table:
375
Sorting Tables
15_579088 ch12.qxd 3/28/05 11:40 AM Page 375
Free JavaScript Editor
Ajax Editor
©
→