JS如下:
var TableUtil = new Object();
TableUtil.Convert = function(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();
}
}
TableUtil.generateCompareCustomTRs = function(iCol,sDataType)
{
return function compare(oTR1,oTR2)
{
var vValue1,vValue2;
if(oTR1.cells[iCol].getAttribute("value"))
{
vValue1 = TableUtil.Convert(oTR1.cells[iCol].getAttribute("value"),sDataType);
vValue2 = TableUtil.Convert(oTR2.cells[iCol].getAttribute("value"),sDataType);
}
else
{
vValue1 = TableUtil.Convert(oTR1.cells[iCol].firstChild.nodeValue,sDataType);
vValue2 = TableUtil.Convert(oTR2.cells[iCol].firstChild.nodeValue,sDataType);
}
if(vValue1 <vValue2)
{
return -1;
}
else if(vValue1 > vValue2)
{
return 1;
}
else
{
return 0;
}
}
}
TableUtil.sortCustomTypeTable = function(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];
}
if(oTable.sortCol == iCol)
{
aTRs.reverse();
}
else
{
aTRs.sort(TableUtil.generateCompareCustomTRs(iCol,sDataType));
}
var oFragment = document.createDocumentFragment();
for(var i = 0;i <aTRs.length;i++)
{
oFragment.appendChild(aTRs[i]);
}
oTbody.appendChild(oFragment);
oTable.sortCol = iCol;
}
HTML如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="JScript1.js" type="text/javascript"></script>
</head>
<body>
<table id="tblSort" border="1" sortCol="">
<thead >
<tr>
<th onclick="TableUtil.sortCustomTypeTable('tblSort',0)" style="cursor:pointer">Type</th>
<th onclick="TableUtil.sortCustomTypeTable('tblSort',1)" style="cursor:pointer">Filename</th>
</tr>
</thead>
<tbody>
<tr>
<td value="doc"><img src="images/wordicon.gif" /></td>
<td>My resume</td>
</tr>
<tr>
<td value="xls"><img src="images/excelicon.gif"/></td>
<td>Fall Budget.xls</td>
</tr>
<tr>
<td value="pdf"><img src="images/acrobaticon.gif" /></td>
<td>How to be a better programmer.pdf</td>
</tr>
<tr>
<td value="doc"><img src="images/wordicon.gif" /></td>
<td>My Old Resume.doc</td>
</tr>
<tr>
<td value="txt"><img src="images/notepadicon.gif" /></td>
<td>Notes from Meeting.txt</td>
</tr>
<tr>
<td value="zip"><img src="images/zippedfoldericon.gif" /></td>
<td>Backups.zip</td>
</tr>
<tr>
<td value="xls"><img src="images/excelicon.gif" /></td>
<td>Spring budget.xls</td>
</tr>
<tr>
<td value="doc"><img src="images/wordicon.gif" /></td>
<td>Job Description - Web Designer.doc</td>
</tr>
<tr>
<td value="pdf"><img src="images/acrobaticon.gif" /></td>
<td>Saved Web Page.pdf</td>
</tr>
<tr>
<td value="doc"><img src="images/wordicon.gif" /></td>
<td>Chapter 12.doc</td>
</tr>
</tbody>
</table>
</body>
</html>