js表頭排序?qū)崿F(xiàn)方法

字號:


    這篇文章主要介紹了js表頭排序?qū)崿F(xiàn)方法,涉及數(shù)字、字母、字符串比較及排序等操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    本文實例講述了js表頭排序?qū)崿F(xiàn)方法。分享給大家供大家參考。
    具體實現(xiàn)方法如下:
    代碼如下:
    <script type=text/javascript>
    //是否遞減排序
    var isdescending = true;
    /*****************************************
    * 要排序的行必須放到<tbody></tbody>標(biāo)簽中
    * tableid:排序表格id
    * colno:排序的列號,即第幾列,從0開始
    * startrowno:排序的開始行號,從0開始
    * sortlength:要排序的行數(shù),
    * type:排序列的類型
    */
    function sort(tableid, colno ,startrowno, sortlength, type)
    {
    //如果要排序的行數(shù)是1或是0,則不對其進(jìn)行排序操作
    if(sortlength<=1){
    return;
    }
    var currtable = document.getelementbyid(tableid);
    var theheader = currtable.outerhtml.substring(0, currtable.outerhtml.indexof('<tbody>')+7)
    var thefooter = currtable.outerhtml.substring(currtable.outerhtml.indexof('</tbody>')-8);
    //這里的行數(shù)是去掉表頭表頭行和表位行的行數(shù)
    var therows = new array(sortlength);
    //對表中的數(shù)據(jù)進(jìn)行循環(huán)
    for(i=startrowno; i<sortlength+startrowno; i++)
    {
    therows[i-startrowno] = new array(currtable.rows[i].cells[colno].innertext.tolowercase(), currtable.rows[i].outerhtml);
    }
    if(type.touppercase()=='number')
    {
    therows.sort(comparenumber);
    }
    else if(type.touppercase()=='date')
    therows.sort(comparedate);
    else if(type.touppercase()=='string')
    therows.sort(comparestring);
    var tableinfo=''
    for(j=0; j<therows.length; j++)
    {
    tableinfo+=therows[j][1];
    }
    isdescending = !isdescending;
    currtable.outerhtml= theheader + tableinfo +thefooter;
    return ;
    }
    //對數(shù)字進(jìn)行比較
    function comparenumber(x, y)
    {
    //對貨幣格式的數(shù)據(jù)進(jìn)行轉(zhuǎn)化
    a = x[0].excludechars(,).trim();
    b = y[0].excludechars(,).trim();
    if(a==){a=0;}
    if(b==){b=0;}
    if(isdescending)
    {
    return parsefloat(b) - parsefloat(a);
    }
    else
    {
    return parsefloat(a) - parsefloat(b);
    }
    }
    //對字符串進(jìn)行比較
    function comparestring(x, y)
    {
    if(isdescending)
    {
    if(x[0]>y[0]) return -1;
    else if(x[0]<y[0]) return 1;
    else return 0;
    }
    else
    {
    if(x[0]<y[0]) return -1;
    else if(x[0]>y[0]) return 1;
    else return 0;
    }
    }
    //對時間進(jìn)行比較
    function comparedate(x,y){
    var arr=x[0].split(-);
    var starttime=new date(arr[0],arr[1],arr[2]);
    var starttimes=starttime.gettime();
    var arrs=y[0].split(-);
    var lktime=new date(arrs[0],arrs[1],arrs[2]);
    var lktimes=lktime.gettime();
    if(isdescending)
    {
    return lktimes - starttimes;
    }
    else
    {
    return starttimes - lktimes;
    }
    }
    //去除字符串中所有指定的字符串
    string.prototype.excludechars = function(chars){
    var matching = new regexp(chars , g) ;
    return this.replace(matching , '') ;
    }
    </script>
    希望本文所述對大家的javascript程序設(shè)計有所幫助。