<html>
<head>
<title>Sort.html</title>
<script type="text/javascript">
function convert(sValue, sDataType) {
switch (sDataType) {
case "int":
return parseInt(sValue);
case "float":
return parseFloat(sValue);
case "date":
return new Date(Date.parse(sValue));
default:
return sValue.toString();
}
}
function generateCompareTRs(iCol, sDataType) {
return function compareTRs(oTR1, oTR2) {
var sValue1 = convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType);
var sValue2 = convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType);
//这里就不可以使用localeCompare方法了,因为数字和日期不支持它,也不可以用"==",因为日期是对象。
if (sValue1 < sValue2) {
return -1;
} else if (sValue1 > sValue2) {
return 1;
} else {
return 0;
}
}
}
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.push(colDataRows[i]);
}
if (oTable.sortCol == iCol){
aTRs.reverse();
} else {
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;
}
</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>
<th onclick="sortTable('tblSort', 2, 'date')" style="cursor:pointer">Birthday</th>
<th onclick="sortTable('tblSort', 3, 'int')" style="cursor:pointer">Age</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
<td>John</td>
<td>7/12/1978</td>
<td>31</td>
</tr>
<tr>
<td>Johnson</td>
<td>Betty</td>
<td>10/15/1977</td>
<td>32</td>
</tr>
<tr>
<td>Henderson</td>
<td>Nathan</td>
<td>02/22/1982</td>
<td>27</td>
</tr>
<tr>
<td>Williams</td>
<td>James</td>
<td>8/19/1980</td>
<td>29</td>
</tr>
<tr>
<td>Gilliams</td>
<td>Michael</td>
<td>5/13/1972</td>
<td>39</td>
</tr>
<tr>
<td>Walker</td>
<td>Matthew</td>
<td>10/19/1981</td>
<td>28</td>
</tr>
</tbody>
</table>
</body>
</html>
posted on 2008-01-24 13:08
周锐 阅读(335)
评论(0) 编辑 收藏 所属分类:
HTML 、
JavaScript