日期:2014-05-16  浏览次数:20363 次

JS 合并表格(方法一)

欢迎讨论

/**
 * table单元格合并
 * 合并规则:要合并的多个td name属性相同,且呈方形连续分布
 * @param {string} tableId
 */
function combineTable(tableId) {
	var oTbl = document.getElementById(tableId);
	var allTds = oTbl.getElementsByTagName("td");
	if(allTds.length < 1) {
		return;
	}
	
	//step 1:查找需要合并的td,规则:相同name出现超过两次的td,就是需要合并的
	var map = new Object();
	for(var i = 0; i < allTds.length; i++) {
		var tmpTdName = allTds[i].getAttribute("name");

		if(tmpTdName) {
			map[tmpTdName] = !map[tmpTdName] ? 1 : Number(map[tmpTdName]) + 1;
		}
	}

	var tdNames = new Array();
	for(var i in map) {
		if(Number(map[i]) > 1) {
			tdNames.push(i);
		}		
	}
	
	//step2 combine tds
        //解决IE下面getElementsByName无效问题
	var commonGetElementsByName = function(parentDom, tagName, name) {
		var result = new Array();
		var doms = parentDom.getElementsByTagName(tagName);

		for (var i = 0; i < doms.length; i++) {
			if (doms[i].getAttribute("name") == name) {
				result.push(doms[i]);
			}
		}

		return result;
	};
	
	var tdsToDelete = new Array();
	for (var i = 0; i < tdNames.length; i++) {
		var tdsToCombine = commonGetElementsByName(oTbl, "td", tdNames[i]);
		var tdFirst = tdsToCombine[0];
		var tdLast = tdsToCombine[tdsToCombine.length - 1];
		var colspan = tdLast.cellIndex - tdFirst.cellIndex + 1;
		var rowspan = 1;
		
		for (var j = 0; j < tdsToCombine.length; j++) {
			var aTd = tdsToCombine[j];
			
			//calculate rowspan
			if (j > 0 && tdsToCombine[j].parentNode != tdsToCombine[j - 1].parentNode) {
				rowspan++;
			}

			//暂存要删除的
			if (aTd != tdFirst) {
				tdsToDelete.push(aTd);
			}
		}

		if(colspan > 1) {
			tdFirst.setAttribute("colspan", colspan);
			tdFirst.colSpan = colspan;
		}
		if(rowspan > 1) {
			tdFirst.setAttribute("rowspan", rowspan);
			tdFirst.rowSpan = rowspan;
		}
	}
	
	//delete at last
	for (var i = 0; i < tdsToDelete.length; i++) {
		tdsToDelete[i].parentNode.removeChild(tdsToDelete[i]);
	}
}

?