↑
Main Page
JavaScript code
Using this methodology, the comparison function returns the correct value no matter which data type is
being used.
Next, you modify the
sortTable()
function to use the new comparison function generator. To do so,
this function also must accept an additional argument indicating the data type to use for the compari-
son. Then, this data type must be passed into the
generateCompareTRs()
function.
function sortTable(sTableID, iCol, sDataType) {
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, sDataType));
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
oTable.sortCol = iCol;
}
With the JavaScript code all done, it’s time to add extra data to the table for the various data types:
<table border=”1” id=”tblSort”>
<thead>
<tr>
<th onclick=”sortTable(‘tblSort’, 0)”
style=”cursor:pointer”>Last Name</th>
<th onclick=”sortTable(‘tblSort’, 1)”
style=”cursor:pointer”>First Name</th>
<th onclick=”sortTable(‘tblSort’, 2, ‘date’)”
style=”cursor:pointer”>Birthday</th>
<th onclick=”sortTable(‘tblSort’, 3, ‘int’)”
style=”cursor:pointer”>Siblings</th>
</tr>
</thead>
<tbody>
It’s important not to use the equality operator (
==
) in this case. Although it works for
strings and numbers (both integer and float), it won’t work for dates. Remember,
dates are objects, not primitive values. This means that the equality operator com-
pares the objects to see if they are the same; it does not compare the values of the
Date
objects. However, the less-than and greater-than symbols use the
valueOf()
method of the
Date
objects to compare their milliseconds representation.
380
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 380
Free JavaScript Editor
Ajax Editor
©
→