首页 > 代码库 > 表格列点击排序

表格列点击排序

实现点击表格列实现排序的效果,按照一列一列的排序

代码如下:

技术分享排序代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table{
            border-collapse: collapse;
        }
        th,td{
            height: 30px;
            width: 80px;
            border: 1px solid black;
            text-align: center;
            margin: 0;

        }
        .content{
            margin: auto;
        }
    </style>
</head>
<body>
<div class="content">
    <table>
        <thead>
           <tr>
               <th>姓名</th>
               <th id="mathBtn">数学</th>
               <th id="artBtn">语文</th>
               <th id="EngBtn">英语</th>
               <th id="allScore">总分</th>
           </tr>
        </thead>
        <tbody>
        <tr><td>小明</td><td>80</td><td>90</td><td>70</td><td>120</td></tr>
        <tr><td>小红</td><td>1</td><td>60</td><td>3</td><td>10</td></tr>
        <tr><td>小刘</td><td>50</td><td>49</td><td>68</td><td>210</td></tr>
        <tr><td>小张</td><td>20</td><td>30</td><td>40</td><td>100</td></tr>
        </tbody>
    </table>
</div>
<script type="text/javascript">
    /*
    *
    *,compare比较函数
    *这里使用了闭包解决for循环问题
    *
    * */
    window.onload=function() {
        var bjuge = false;
        var body = document.getElementsByTagName("tbody")[0];
        var th = document.getElementsByTagName("th");//为什么点击事件没有发生呢
        for (var k = 1; k < 5; k++) {
                th[k].onclick =function(k){
                    return function () {
                    var temp = new Array(4);
                    for (var i = 0; i < 4; i++) {
                        temp[i] = body.children[i].getElementsByTagName("td")[k].innerText;
                    }
                    function compare2(value1, value2) {
                        return value1 - value2;
                    }
                    if (bjuge == true) {
                        temp = temp.sort(compare2);
                        bjuge = false;
                    } else {
                        temp = temp.reverse(temp.sort(compare2));
                        bjuge = true;
                    }
                    for (var m = 0; m < 4; m++) {
                        for (var j = 0; j < 4; j++) {
                            if (body.children[j].getElementsByTagName("td")[k].innerText == temp[m]) {
                                body.children[m].parentNode.insertBefore(body.children[j], body.children[m]);
                            }
                        }
                    }
                }
            }(k)
        }
    }
    </script>
</body>
</html>

 笔记:

表格列点击排序