html表格cell合併插件

數據展現時須要合併部分數據本身寫了一個簡單插件html

合併前:數組

合併後:this

調用示例:spa

        var trs = $('table#dataList tbody tr').not('#demo').get();
        var cellMerger = new CellMerger();
        //合併大區
        cellMerger.merge(trs, new Array('MSGNUMBER','LARGEAREA'), new Array('LARGEAREA'));
        cellMerger.merge(trs, new Array('MSGNUMBER'), new Array('option','statusName','TITLE','MSGNUMBER','CREATEOWNER','CTIME'));

參數說明:prototype

第一個參數是要處理合並的行, 第二個參數是合併條件, 好比列1和列2對應值相等什麼的, 支持多條件, 第三個參數是要合併的列插件

合併插件:code

function CellMerger(){
}

CellMerger.prototype.merge = function (trs, needIndexs, mergedIndexes){
    var mergeds = new Array();
    for(x in mergedIndexes){
        mergeds.push("td[index="+mergedIndexes[x]+"]");
    }
    var needs = new Array();
    for(x in needIndexs){
        needs.push("td[index="+needIndexs[x]+"]");
    }
    this.mergeCell(trs, needs, mergeds);
};

CellMerger.prototype.conditionMatch = function (targets, currents){
    if(targets.length==0 && currents.length==0){
        return true;
    }
    if(targets.length != currents.length){
        return false;
    }
    for(x in targets){
        if(targets[x]!=currents[x]){
            return false;
        }
    }
    return true;
};

CellMerger.prototype.rowspanAndRemove = function (trs, curIndex, sames, mergeds){
    var rowspan=sames.length+1;
    for(x in mergeds){
        $(trs[curIndex]).children(mergeds[x]).attr('rowspan',rowspan);
    }
    for(var j=0;j<sames.length;j++){
        for(x in mergeds){
            $(trs[sames[j]]).children(mergeds[x]).remove();
        }
    }
};

CellMerger.prototype.mergeCell = function (trs, needs, mergeds){
    var targets = new Array();
    var curIndex = 0;
    var sames = new Array();
    for(var i=0;i<trs.length;i++){
        var current = new Array();
        for(x in needs){
            current[x] = $(trs[i]).children(needs[x]).html();
        }
        if(targets.length == 0){
            //初始化比對條件
            curIndex = i;
            for(x in needs){
                targets[x] = $(trs[i]).children(needs[x]).html();
            }
        }
        else{
            if(this.conditionMatch(targets, current)){
                sames.push(i);
                //最後一條進行向前合併
                if(i == trs.length-1 && sames.length>0){
                    this.rowspanAndRemove(trs, curIndex, sames, mergeds);
                }
            }
            else{
                //合併類似項
                if(sames.length>0){
                    this.rowspanAndRemove(trs, curIndex, sames, mergeds);
                }    
                //清空數組, 重置比較索引
                curIndex = i;
                sames = new Array();
                for(x in needs){
                    targets[x] = $(trs[i]).children(needs[x]).html();
                }
            }
        }
    }
};
相關文章
相關標籤/搜索