jquery 实现表格排序功能

$(function(){
    //存入点击列的每一个TD的内容;
    var aTdCont = [];

   //点击列的索引值
    var thi = 0
    
    //重新对TR进行排序
    var setTrIndex = function(tdIndex){
        for(i=0;i<aTdCont.length;i++){
            var trCont = aTdCont[i];
            $("tbody tr").each(function() {
                var thisText = $(this).children("td:eq("+tdIndex+")").text();
                if(thisText == trCont){
                    $("tbody").append($(this));
                }
             });        
        }
    }
    
    //比较函数的参数函数
    var compare_down = function(a,b){
            return a-b;
    }
    
    var compare_up = function(a,b){
            return b-a;
    }
    
    //比较函数
    var fSort = function(compare){
        aTdCont.sort(compare);
    }
    
    //取出TD的值,并存入数组,取出前二个TD值;
    var fSetTdCont = function(thIndex){
            $("tbody tr").each(function() {
                var tdCont = $(this).children("td:eq("+thIndex+")").text();
                aTdCont.push(tdCont);
            });
    }
    //点击时需要执行的函数
    var clickFun = function(thindex){
        aTdCont = [];
        //获取点击当前列的索引值
        var nThCount = thindex;
        //调用sortTh函数 取出要比较的数据
        fSetTdCont(nThCount);
    }
    
    //点击事件绑定函数
    $("th").toggle(function(){
        thi= $(this).index();
        clickFun(thi);
        //调用比较函数,降序
        fSort(compare_up);
        //重新排序行
        setTrIndex(thi);
    },function(){
        clickFun(thi);
        //调用比较函数 升序
        fSort(compare_down);
        //重新排序行
        setTrIndex(thi);
    })    
})

主要思路:

  因为JS有SORT的方法,对数组进行排序,那么通过个方法,我们就会想到数组了。

  1.点标表格标头的时候,取出点击的是那一列。即列的索引值。因为下面要进行排序的就是该列。所以我要知道是点的那一列。

  2.对表格的数据部分,也就是tbody部分,进行点击的列的取值,把这些值存入到一个数组当中。

  3.将存入数据的数组,通过SORT方法进行排序。(这里写了两种,升,或降,因为是点击时要切换排序的方式。第一次降,第二次升,第三降,第四升,依次进行)

  4.将排序好的数组的值进行遍历,在遍历过程中,和每一行TR的点击列的那个TD当中的数据进行一个比较。如果相等,就插入到tbody的最后去.(最先插入的,将是在第一行。)

demo下载:

扫描二维码关注公众号,回复: 270446 查看本文章

原文地址:http://www.cnblogs.com/lufy/archive/2012/05/23/2515142.html

参考地址:http://www.cnblogs.com/wuzhsh/archive/2012/07/26/2609312.html

猜你喜欢

转载自zgphacker2010.iteye.com/blog/2386317