js实现表格操作-排序

用js实现表格操作,点击th,则根据该th所属列的数据排序,点击一次降序,第二次点击升序。

表格代码:

<table>
<thead>
    <tr>
        <th>姓名th>
        <th>力量th>
        <th>敏捷th>
        <th>实力th>
    tr>
thead>
<tbody>
    <tr>
        <td>德鲁伊td>
        <td>17td>
        <td>24td>
        <td>13td>
    tr>
    <tr>
        <td>德神之王td>
        <td>19td>
        <td>15td>
        <td>20td>
    tr>
    <tr>
        <td>月之骑士td>
        <td>15td>
        <td>22td>
        <td>16td>
    tr>
    <tr>
        <td>德鲁剑客td>
        <td>23td>
        <td>15td>
        <td>14td>
    tr>
tbody>
table>

js代码:

window.onload=function(){
        var tbody=document.getElementsByTagName('tbody');
        var th=document.getElementsByTagName('th');
        var r=tbody[0].rows.length;
        var c=tbody[0].rows[0].cells.length;
        var arr2=[];
        for(var i=0;i0].rows[i];

        }
        for(var i=0;ifunction(n){
                    var count=0;//记录点击次数
                    th[i].onclick=function(){

                    if(count==0){
                        if(n==0){
                        strSortUp(arr2,n);

                        }
                        sortUp(arr2,n);
                        count=1;
                    }else{
                        if(n==0){
                        strSortDown(arr2,n);
                        }
                        sortDown(arr2,n);
                        count=0;
                        }
                        var str="";
                        var html="";
                        for(var k=0;kfor(var j=0;j""+arr2[k].children[j].innerText+"";
                            }
                            html+=""+str+"";
                            str="";

                        }
                        tbody[0].innerHTML=html;
                    }


                })(i);

                }
    }
    //数字降序
    function sortUp(arr,n){
        arr.sort(function(a,b){
                                return a.children[n].innerText-b.children[n].innerText;
        });
    }
    //数字升序
    function sortDown(arr,n){
        arr.sort(function(a,b){
                                return b.children[n].innerText-a.children[n].innerText;
        });
    }
    //字符串降序
    function strSortUp(arr,n){
        var i=0;
        arr.sort(function(a,b){
            return  a.children[n].innerText.localeCompare(b.children[n].innerText);
        });

    }
//字符串降升序
    function strSortDown(arr,n){
        arr.sort(function(a,b){
                        return  -(a.children[n].innerText.localeCompare(b.children[n].innerText));
                                });
    }

你可能感兴趣的:(js)