js表格排序

来源:互联网 发布:电脑mac地址怎么查 编辑:程序博客网 时间:2024/05/23 20:18
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>sortTable.html</title>    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="this is my page">    <meta http-equiv="content-type" content="text/html; charset=gbk"><script type="text/javascript">function sortTable(sTableId, iCol, sDataType){var oTable = document.getElementById(sTableId);//获得表var oTBody = oTable.tBodies[0];//获得放数据的body,因为该表格只有一个tbody,所以直接用[0]var colRows = oTBody.rows;//获得tbody里所有的trvar aTRs = new Array();//声明一个数组for(var i = 0; i < colRows .length; i++){ aTRs[i] = colRows[i];//将tr依次放入数组中;}if(oTable.sortCol == iCol){ aTRs.reverse();//如果当前要排的列和上次排的列是一样的,就直接逆向排序;也就是说连着对一列点两次,就会进行升序,降序的转换.}else{ aTRs.sort(getSortFunction(iCol, sDataType));//排序,并且传入一个获得到的比较函数;}   var oFragement = document.createDocumentFragment();//创建文档碎片,用来存放排好的trfor(var i = 0; i < aTRs.length; i++){ oFragement.appendChild(aTRs[i]);//将tr绑定到碎片上.}oTBody.appendChild(oFragement);//将碎片绑定在表格上oTable.sortCol = iCol;//记住当前列,这个可以用来判断是对数组进行反向排序还是重新按列排;}//排序函数 iCol列数 sDataType数据类型function getSortFunction(iCol, sDataType){return function compareTRs(oTR1, oTR2){   var vValue1, vValue2;     if(oTR1.cells[iCol].getAttribute("value")){vValue1 = convert(oTR1.cells[iCol].getAttribute("value"), sDataType);vValue2 = convert(oTR2.cells[iCol].getAttribute("value"), sDataType);   }else{vValue1 = convert(oTR1.cells[iCol].firstChild.nodeValue, sDataType)vValue2 = convert(oTR2.cells[iCol].firstChild.nodeValue, sDataType)   }      if(vValue1 < vValue2){return -1;   } else if(vValue1 > vValue2){return 1;   }else{return 0;   }}}//将字符串转换为制定类型的数据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();} }</script>  </head>    <body>   <table id="tblSort" border="0" width="80%" cellpadding="0" cellspacing="0"><thead>   <tr>  <th onclick="sortTable('tblSort', 0)" style="cursor:pointer">类型</th>  <th onclick="sortTable('tblSort', 1)" style="cursor:pointer">文件名</th>  <th onclick="sortTable('tblSort', 2, 'date')" style="cursor:pointer">创建日期</th>  <th onclick="sortTable('tblSort', 3, 'int')" style="cursor:pointer">文件大小</th>   </tr></thead><tbody>   <tr align="center">  <td value="doc"><img src="images/wordIcon.gif"</td>  <td>Word 文档</td>  <td>7/12/2008</td>  <td>3</td>   </tr>   <tr align="center">  <td value="xls"><img src="images/xlsIcon.gif"</td>  <td>Excel 文档</td>  <td>5/11/2008</td>  <td>6</td>   </tr>   <tr align="center">  <td value="pdf"><img src="images/pdfIcon.gif"</td>  <td>PDF 文档</td>  <td>7/5/2007</td>  <td>8</td>   </tr></tbody></table>   </body></html>

0 0
原创粉丝点击