↑
Main Page
array
This section of code creates an array called
aTRs
and fills it with references to the
<tr/>
elements. Doing
this doesn’t remove the
<tr/>
elements from the table because you are only storing pointers, not the
actual elements.
The next step is to sort the array using the
compareTRs()
function:
function sortTable(sTableID) {
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.push(colDataRows[i]);
}
aTRs.sort(compareTRs);
//...
}
After this, all the
<tr/>
elements are in order in the array, but the order on the page hasn’t changed. To
actually change the order on the page, you add each row back in order. The fastest way to do this is to
create a document fragment and add all
<tr/>
elements to it in the correct order. Then, you can use
appendChild()
to add all the child nodes from the document fragment back into the
<tbody/>
element.
function sortTable(sTableID) {
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(compareTRs);
var oFragment = document.createDocumentFragment();
for (var i=0; i < aTRs.length; i++) {
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
This code creates a document fragment and adds all the
<tr/>
elements to it, which effectively removes
them from the table (Figure 12-2). Then, the children of the fragment are added back to the
<tbody/>
element. Remember, when you use
appendChild()
and pass it a document fragment, all the child
nodes of the fragment are appended, not the fragment itself.
372
Chapter 12
15_579088 ch12.qxd 3/28/05 11:40 AM Page 372
Free JavaScript Editor
Ajax Editor
©
→