JS学习之表格的排序简单实例

JS学习之表格的排序简单实例

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <input id="btn1" type="button" value="排序">
    <table id="tab1" width="200" border="1" cellpadding="14">
      <thead>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
      </thead>
      <tbody>
        <tr>
          <td>2</td>
          <td>张三</td>
          <td>20</td>
        </tr>
        <tr>
          <td>4</td>
          <td>李四</td>
          <td>25</td>
        </tr>
        <tr>
          <td>3</td>
          <td>赵龙</td>
          <td>30</td>
        </tr>
        <tr>
          <td>1</td>
          <td>孙河</td>
          <td>21</td>
        </tr>
      </tbody>
    </table>
    <script type="text/javascript">
      var oTab=document.getElementById('tab1');
      var oBtn=document.getElementById('btn1');
      oBtn.onclick=function(){
        var arr=[]
        for(i=0;i<oTab.tBodies[0].rows.length;i++){
          arr[i]=oTab.tBodies[0].rows[i];
        }
        arr.sort(function(tr1,tr2){
        var n1=parseInt(tr1.cells[0].innerHTML);  
        var n2=parseInt(tr2.cells[0].innerHTML);
        return n1-n2;
        })
        for(i=0;i<arr.length;i++){
          oTab.tBodies[0].appendChild(arr[i])
        }
      }
    </script>
  </body> 
</html>

相关推荐