JS 合并表格(方法二)

function combineTable2(tableId) {
	var oTbl = document.getElementById(tableId); 
	var tdsToCombine = [];
	var allTds = [];
	for(var i = 0; i < oTbl.rows.length; i++){
		for(var j = 0; j < oTbl.rows[i].cells.length; j++){
			var name = oTbl.rows[i].cells[j].getAttribute("name");
			var obj = new Object();
			obj.name = name;
			obj.row = i;
			obj.cell = j;
			allTds.push(obj);		
			
			if(name) {
				var nameExists = false;
				for(var k = 0; k < tdsToCombine.length; k++) {
					if(tdsToCombine[k].name == name) {
						nameExists = true;
						break;
					}
				}
				if(!nameExists) {
					tdsToCombine.push(obj);	
				}				
			}
		}
	}

	var delArr = [];
	for(var c = 0; c < tdsToCombine.length; c++){
		var o1 = tdsToCombine[c];
		var beginIndex = o1.row * oTbl.rows.length + o1.cell + 1;
		for(var d = beginIndex; d < allTds.length;d++){
			var o2 = allTds[d];
			if(o2.name == o1.name){
				if(o2.row == o1.row && o2.cell != o1.cell ){
					oTbl.rows[o1.row].cells[o1.cell].colSpan++;
				} else if(o2.cell == o1.cell && o2.row != o1.row ){
					oTbl.rows[o1.row].cells[o1.cell].rowSpan++;	
				}				
				delArr.push(oTbl.rows[o2.row].cells[o2.cell]);
			}
		}
	}
	
	for(var i = 0; i < delArr.length; i++) {
		delArr[i].parentNode.removeChild(delArr[i]);
	}
}

 

你可能感兴趣的:(js)