合并思路如下:
1、根据单元格内容或单元格属性找出需要合并的单元格
2、修改起始单元格colspan值
3、删除多余的单元格
单元格合并代码如下:
/************************************* table单元格合并 ***********************************************
合并指定table 指定列 相同数据的单元格 table:table对象 colInx:需要合并的列的index columns:table总列数
opts:{columns:总列数,skipNull:是否忽略空单元格的合并 mergeAttrName }
**********************************************************************************************/
mergeTalbeVCells = function(table,colInx,opts){
var option = {skipNull:false};
$.extend(option,opts);
var cols = option.columns || table.rows[0].cells.length;
var colArr = [];
var rows = table.rows.length;
var n = 1;
for(var i=0;i<rows;i++){
var currtxt = '';
if(option.mergeAttrName){
currtxt = table.rows[i].cells[colInx - (cols - table.rows[i].cells.length)].getAttribute(option.mergeAttrName);
}else{
currtxt = table.rows[i].cells[colInx - (cols - table.rows[i].cells.length)].innerText;
}
var nexttxt;
if(i < rows-1){
if(option.mergeAttrName){
nexttxt = table.rows[i+1].cells[colInx - (cols - table.rows[i+1].cells.length)].getAttribute(option.mergeAttrName);
}else{
nexttxt = table.rows[i+1].cells[colInx - (cols - table.rows[i+1].cells.length)].innerText;
}
}else{
colArr[colArr.length] = {rowInx:((i+1)-n),rowSpan:n};
}
if(currtxt != nexttxt){
colArr[colArr.length] = {rowInx:(i-n+1),rowSpan:n};
n = 0;
}else if(currtxt=="" && nexttxt==""){
// 是否忽略空字符
if(option.skipNull){
colArr[colArr.length] = {rowInx:0,rowSpan:1};
n = 0;
}
}
n++;
}
// 合并相同数据的单元格
for(var i=0;i<colArr.length;i++){
table.rows[colArr[i].rowInx].cells[colInx - (cols - table.rows[colArr[i].rowInx].cells.length)].rowSpan = colArr[i].rowSpan;
for(var j=1;j<colArr[i].rowSpan;j++){
table.rows[colArr[i].rowInx*1+j].deleteCell(colInx - (cols - table.rows[colArr[i].rowInx*1+j].cells.length));
}
}
}
还原合并代码如下:
/******* 还原合并 *******/
var restoreMergeTable = function(table,colInx,opts){
var option = {skipNull:false};
$.extend(option,opts);
var cols = option.columns || table.rows[0].cells.length;
var colArr = [];
var rows = table.rows.length;
var n = 1;
for(var i=0;i<rows;i++){
var cell = getCellByColInx(table.rows[i],colInx);
if(!cell) continue;
var rowSpan = cell.getAttribute("rowSpan");
if(rowSpan<2) continue;
for(var ri=1;ri<rowSpan;ri++){
copyCell(table.rows[i+ri].insertCell(0),cell,_this.option.userDatas);
}
cell.rowSpan = 1;
}
/************** 复制单元格 **************/
function copyCell(res_cell,target_cell,attributes){
res_cell.innerHTML = target_cell.innerHTML;
if(attributes){
for(var i=0,len=attributes.length;i<len;i++){
res_cell.setAttribute(attributes[i],target_cell.getAttribute(attributes[i]));
}
}
res_cell.setAttribute("columnId",target_cell.getAttribute("columnId"));
}
}