JS連結表(方法一)
2428 ワード
歓迎します
/**
* 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]);
}
}