当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS实现简单表格排序操作示例

JS实现简单表格排序操作示例

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文实例讲述了js实现简单表格排序操作。分享给大家供大家参考,具体如下:

<!doctype>
<html>
<head>
  <meta http-equiv="content-type" content="text/html" charset="utf-8">
  <title>sort table</title>
  <style>
    *{
      margin:0px;
      padding:0px;
    }
    body{
      background:#ccc;
    }
    table{
      width:350px;
      margin:0 auto;
      background-color:#eee;
    }
    table th{
      cursor:hand;
      padding:5px 0;
      background-color:#999;
    }
    table td{
      background-color:#fff;
      font-size:16px;
      font-weight:normal;
      text-align:center;
      line-height:30px;
    }
  </style>
  <script language="javascript">
    function sortcells(type){
      var tbs=document.getelementsbytagname("table")[0];
      var arr=[];
      var arr2=[];
      for(var i=1;i<tbs.rows.length;i++){
        var text=tbs.rows[i].cells[type].innertext;
        arr.push(text);
        arr2[text]=i;
      }
      if(type==0){
        arr.sort(function(a,b){return a-b});
      }else{
        arr.sort();
      }
      var temp="";
      for(var j=1;j<tbs.rows.length;j++){
        temp=tbs.rows[j].cells[0].innertext;
        tbs.rows[j].cells[0].innertext=tbs.rows[arr2[arr[j-1]]].cells[0].innertext;
        tbs.rows[arr2[arr[j-1]]].cells[0].innertext=temp;
        temp=tbs.rows[j].cells[1].innertext;
        tbs.rows[j].cells[1].innertext=tbs.rows[arr2[arr[j-1]]].cells[1].innertext;
        tbs.rows[arr2[arr[j-1]]].cells[1].innertext=temp;
        temp=tbs.rows[j].cells[2].innertext;
        tbs.rows[j].cells[2].innertext=tbs.rows[arr2[arr[j-1]]].cells[2].innertext;
        tbs.rows[arr2[arr[j-1]]].cells[2].innertext=temp;
//        console.log(arr2);
        for(var i=1;i<tbs.rows.length;i++){
          var text=tbs.rows[i].cells[type].innertext;
          arr2[text]=i;
        }
      }
    }
  </script>
</head>
<body>
<center>sort table</center>
<table border="0">
  <tr>
    <th onclick="sortcells(0);">序号</th>
    <th onclick="sortcells(1);">姓名</th>
    <th onclick="sortcells(2);">日期</th>
  </tr>
  <tr>
    <td>2</td>
    <td>bb</td>
    <td>2015-09-12</td>
  </tr>
   <tr>
    <td>3</td>
    <td>cc</td>
    <td>2015-07-12</td>
  </tr>
   <tr>
    <td>1</td>
    <td>aa</td>
    <td>2015-09-11</td>
  </tr>
   <tr>
    <td>4</td>
    <td>dd</td>
    <td>2015-06-12</td>
  </tr>
</table>
</body>
</html>

运行效果:

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript表格(table)操作技巧大全》、《javascript操作dom技巧总结》、《javascript遍历算法与技巧总结》、《javascript数学运算用法总结》、《javascript数据结构与算法技巧总结》、《javascript查找算法技巧总结》及《javascript错误与调试技巧总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网