实现Table多类间不同类型的顺反(逆序)排序
JS如下:
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.generateCompareTypeTRs = function(iCol,sDataType)
{
return function compareTypeTRs(oTR1,oTR2)
{
var vValue1 = TableUtil.Convert(oTR1.cells[iCol].firstChild.nodeValue,sDataType);
var vValue2 = TableUtil.Convert(oTR2.cells[iCol].firstChild.nodeValue,sDataType);
if(vValue1<vValue2)
{
return -1;
}
else if(vValue1>vValue2)
{
return 1;
}
else
{
return 0;
}
}
}
TableUtil.sortTypeTable = 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.generateCompareTypeTRs(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.sortTypeTable('tblSort',0)" style="cursor:pointer">Last Name</th>
<th onclick="TableUtil.sortTypeTable('tblSort',1)" style="cursor:pointer">First Name</th>
<th onclick="TableUtil.sortTypeTable('tblSort',2,'date')" style="cursor:pointer">Birthday</th>
<th onclick="TableUtil.sortTypeTable('tblSort',3,'int')" style="cursor:pointer">Siblings</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
<td>Jhon</td>
<td>7/12/1978</td>
<td>2</td>
</tr>
<tr>
<td>Johnson</td>
<td>Betty</td>
<td>10/15/1977</td>
<td>4</td>
</tr>
<tr>
<td>Henderson</td>
<td>Nathan</td>
<td>2/25/1977</td>
<td>4</td>
</tr>
<tr>
<td>Williams</td>
<td>James</td>
<td>7/8/1980</td>
<td>4</td>
</tr>
<tr>
<td>Gilliam</td>
<td>Michael</td>
<td>7/22/1949</td>
<td>4</td>
</tr>
<tr>
<td>Walker</td>
<td>Matthew</td>
<td>1/14/2000</td>
<td>3</td>
</tr>
<tr>
<td>Vihone</td>
<td>He</td>
<td>11/5/1983</td>
<td>3</td>
</tr>
<tr>
<td>Maggie</td>
<td>Yang</td>
<td>9/23/1984</td>
<td>3</td>
</tr>
<tr>
<td>Zhiyi</td>
<td>Lin</td>
<td>12/5/1988</td>
<td>2</td>
</tr>
<tr>
<td>Alex</td>
<td>Lee</td>
<td>7/12/1984</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
</html>