理论支撑N列合并,前提是数据已经按照第一列分类排序。
//datagrid的id
var tableID = 'XXXX';
//要合并的列
var colList = ['列名1','列名2','列名3'];
//每次合并列的标记
var resultInbdex = null;
//合并列
for(var i=0;i<cols.length;i++)
resultInbdex = mergeCellsByField("dg", cols[i], resultInbdex);
function mergeCellsByField(tableID,colList,lastResultIndex) {
var resultIndex = new Array();//当前合并行数标记
var ColArray = colList.split(",");//指定合并列
var tTable = $("#" + tableID);//表格
var rowdata = tTable.datagrid("getRows");//行数据
var TableRowCnts = rowdata.length;//总行数
var tmpA;//累加行数
var PerTxt = "";//上一行
var CurTxt = "";//当前行
for (j = ColArray.length - 1; j >= 0; j--) {//列
PerTxt = "";
tmpA = 1;
for (i = 0; i <= TableRowCnts; i++) {//行
if (i == TableRowCnts) {
CurTxt = "";
}else {
CurTxt = rowdata[i][ColArray[j]];
}
if(lastResultIndex!=null){
var parentInext = lastResultIndex[0];
if(i>=parentInext){//不超父列
var currIndex = i - tmpA;
resultIndex.push(i);
if(tmpA > 1 ){
tTable.datagrid("mergeCells", {
index: currIndex,
field: ColArray[j],//合并字段
rowspan: tmpA,
colspan: null
});
}
tmpA = 1;
lastResultIndex.shift();
}else{
if(i==0){//第一行不需合并记录行号
PerTxt = CurTxt;
continue;
}else if (PerTxt == CurTxt) {//内容相等
tmpA += 1;
}else {
var currIndex = i - tmpA;
resultIndex.push(i);
if(tmpA > 1 ){
tTable.datagrid("mergeCells", {
index: currIndex,
field: ColArray[j],//合并字段
rowspan: tmpA,
colspan: null
});
}
tmpA = 1;
}
}
}else{
if(i==0){//第一行不需合并记录行号
PerTxt = CurTxt;
continue;
}else if (PerTxt == CurTxt) {//内容相等
tmpA += 1;
}else {
var currIndex = i - tmpA;
resultIndex.push(i);
if(tmpA > 1 ){
tTable.datagrid("mergeCells", {
index: currIndex,
field: ColArray[j],//合并字段
rowspan: tmpA,
colspan: null
});
}
tmpA = 1;
}
}
PerTxt = CurTxt;
}
}
return resultIndex;
}