zoukankan      html  css  js  c++  java
  • 每天一个JS 小demo之表单排序。主要知识点:DOM中的表单操作,节点操作

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript">
    window.onload = function(){
    var input = document.querySelectorAll('input');
    var table = document.querySelector('table');
    var rows = table.tBodies[0].rows;
    var arrRows = [];
    /* 因为只能对数组排序,所以把tr都放入数组 */
    for(var i = 0; i < rows.length; i++){
    arrRows.push(rows[i]);
    }
    // arrRows.sort(function(a,b){
    // return b.cells[1].innerHTML - a.cells[1].innerHTML;
    // //根据tr中的第1个单元格中的内容进行排序
    // });
    // arrRows.forEach(function(tr){
    // //按照排号的顺序,重新把tr放入tbody
    // table.tBodies[0].appendChild(tr);
    // });
    //console.log(arrRows);
    input[0].onclick = function(){
    arrRows.sort(function(a,b){
    return b.cells[1].innerHTML - a.cells[1].innerHTML;
    //根据tr中的第1个单元格中的内容进行排序
    });
    arrRows.forEach(function(tr){
    //按照排号的顺序,重新把tr放入tbody
    table.tBodies[0].appendChild(tr);
    });
    }
    input[1].onclick = function(){
    arrRows.sort(function(a,b){
    return a.cells[1].innerHTML - b.cells[1].innerHTML;
    //根据tr中的第1个单元格中的内容进行排序
    });
    arrRows.forEach(function(tr){
    //按照排号的顺序,重新把tr放入tbody
    table.tBodies[0].appendChild(tr);
    });
    }
    };
    </script>
    </head>
    <body>
    <table border="1" width="400" align="center">
    <thead>
    <tr>
    <th>水果</th>
    <th>单价(¥)</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <th>苹果</th>
    <th>54.5</th>
    </tr>
    <tr>
    <th>橘子</th>
    <th>24.5</th>
    </tr>
    <tr>
    <th>西瓜</th>
    <th>33.8</th>
    </tr>
    <tr>
    <th>香蕉</th>
    <th>13.8</th>
    </tr>
    </tbody>
    <tfoot>
    <tr>
    <td colspan="2" style="text-align: center;">
    <input type="button" value="价格从高到低排列">
    <input type="button" value="价格从低到高排列">
    </td>
    </tr>
    </tfoot>
    </table>
    </body>
    </html>

  • 相关阅读:
    11.正则表达式的一些简单应用
    10.JavaScript距离生日还有多少天、根据出生年月日计算年龄、打印当前月份每天的星期
    9.JavaScript获取当前时间,返回格式年-月-日 时:分:秒
    8.JavaScript获取一个从最小值到最大值的随机数
    7.JavaScript数组乱序排序
    6.JavaScript中的new.target
    5.JavaScript自定义数组排序
    2-9 随机模块
    2-8 四则运算
    1-22Python练习题1-1
  • 原文地址:https://www.cnblogs.com/catEatBird/p/7003778.html
Copyright © 2011-2022 走看看