<html>
<head>
<title>Sort.html</title>
<script type="text/javascript">
function generateCompareTRs(iCol) {
return function compareTRs(oTR1, oTR2) {
var sValue1 = oTR1.cells[iCol].firstChild.nodeValue;
var sValue2 = oTR2.cells[iCol].firstChild.nodeValue;
return sValue1.localeCompare(sValue2);
}
}
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.push(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);
}
</script>
</head>
<body>
This is my HTML page. <br>
<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>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
<td>John</td>
</tr>
<tr>
<td>Johnson</td>
<td>Betty</td>
</tr>
<tr>
<td>Henderson</td>
<td>Nathan</td>
</tr>
<tr>
<td>Williams</td>
<td>James</td>
</tr>
<tr>
<td>Gilliams</td>
<td>Michael</td>
</tr>
<tr>
<td>Walker</td>
<td>Matthew</td>
</tr>
</tbody>
</table>
</body>
</html>
逆序排列:
上面只对表格进行了排列,如果要实现想Microsoft Outlook那样,第一次点击是排序,如果再点击一次,将会对此列进行逆序排列。
修改以后的代码为:
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.push(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;
}
posted on 2008-01-24 12:24
周锐 阅读(231)
评论(0) 编辑 收藏 所属分类:
HTML 、
JavaScript