html表格cell合并插件

数据展示时需要合并部分数据自己写了一个简单插件

合并前:

html表格cell合并插件_第1张图片

合并后:

html表格cell合并插件_第2张图片

调用示例:

        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'));

参数说明:

第一个参数是要处理合并的行, 第二个参数是合并条件, 比如列1和列2对应值相等什么的, 支持多条件, 第三个参数是要合并的列

合并插件:

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();
                }
            }
        }
    }
};

 

你可能感兴趣的:(html)