日期:2014-05-16 浏览次数:20481 次
利用js对表格进行排序,本人觉得很有用,把书上的代码打出来给大家看看。
<html>
<head>
<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 generateCompateTRs(iCol,sDataType)
{
return function compareTRs(oTR1,oTR2)
?????? {
??????
?????? ? if(oTR1.cells[iCol].getAttribute("value"))
?????? ? {
?????? ? var value1 = convert(oTR1.cells[iCol].getAttribute("value"),sDataType);
?????? var value2 = convert(oTR2.cells[iCol].getAttribute("value"),sDataType);
?????? ? }
?????? ? else
?????? ? {
?????? ? var value1 = convert(oTR1.cells[iCol].firstChild.nodeValue,sDataType);
?????? var value2 = convert(oTR2.cells[iCol].firstChild.nodeValue,sDataType);
?????? ? }
??????
?????? if(value1 < value2)
?????? {
?????? return -1;
?????? }
?????? else if(value1 > value2)
?????? {
?????? 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[i]=colDataRows[i];
}
aTRs.sort(generateCompateTRs(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>
<form>
<center>
<table border = "1", id="tblSort">
<thead>
<tr>
<th onclick="sortTable('tblSort',0)"
style = "cursor:pointer">LastName</th>
<th onclick="sortTable('tblSort',1)"
style = "cursor:pointer">FirstName</th>
<th onclick="sortTable('tblSort',2,'date')"
style = "cursor:pointer">Birthday</th>
<th onclick="sortTable('tblSort',3,'int')"
style = "cursor:pointer">Siblings</th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith</td>
<td>John</td>
<td>7/12/1987</td>
<td>2</td>
</tr>
<tr>
<td>Johson</td>
<td>Betty</td>
<td>10/15/1989</td>
<td>2</td>
</tr>
<tr>
<td>Yang</td>
<td>Han</td>
<td>5/6/1977</td>
<td>1</td>
</tr>
<tr>
<td>Hen</td>
<td>Huan</td>
<td>1/5/1988</td>
<td>6</td>
</tr>
<tr>
<td>Qiu</td>
<td>He</td>
<td>8/8/1999</td>
<td>100</td>
</tr>
</center>
</form>
</body>
</html>
?