{ if(tabObj != null) { var i,j var intSpan var strTemp for(i = 0i <tabObj.rows.lengthi++) { intSpan = 1 strTemp = tabObj.rows[i].cells[colIndex].innerText for(j = i + 1j <tabObj.rows.lengthj++) {if(strTemp == tabObj.rows[j].cells[colIndex].innerText){ intSpan++tabObj.rows[i].cells[colIndex].rowSpan = intSpantabObj.rows[j].cells[colIndex].style.display = "none" }else{ break } } i = j - 1 } }}
为什么要用js呢?table本身就有合并单元格的功能,其实如果你用js也是给table添加对应的样式。具体代码如下:
<style>table{ border-collapse:collapse}
table td{ border:2px solid #ddd width:50px height:25px text-align:center}
</style>
<table>
<tr>
<td colspan="2">123</td> //横向合并单元格
<td>456</td>
<td>789</td>
</tr>
<tr>
<td rowspan="2">123</td> //竖向合并单元格
<td>456</td>
<td>456</td>
<td>456</td>
</tr>
<tr>
<td>123</td>
<td>456</td>
<td>456</td>
</tr>
</table>
JS合并单元格、JavaScript单元格合并<html>
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">
<title>合并表格</title>
<script>
//功能:合并表格
//参数:tb-需要合并的表格ID
//参数:colLength--需要对前几列进行合并,比如,
//想合并前两列,后面的数据列忽略合并,colLength应为2
//缺省表示对全部列合并
//data:2011.11.06
///////////////////////////////////////////////
function uniteTable(tb,colLength){
//检查表格是否规整
if(!checkTable(tb)) return
var i=0
var j=0
var rowCount=tb.rows.length//行数
var colCount=tb.rows[0].cells.length//列数
var obj1=null
var obj2=null
//为每个单元格命名
for(i=0i<rowCounti++){
for(j=0j<colCountj++){
tb.rows[i].cells[j].id="tb__" + i.toString() + "_" + j.toString()
}
}
//逐列检查合并
for(i=0i<colCounti++){
if(i==colLength) return
obj1=document.getElementById("tb__0_"+i.toString())
for(j=1j<rowCountj++){
obj2=document.getElementById("tb__"+j.toString()+"_"+i.toString())
if(obj1.innerText==obj2.innerText){
obj1.rowSpan++
obj2.parentNode.removeChild(obj2)
}else{
obj1=document.getElementById("tb__"+j.toString()+"_"+i.toString())
}
}
}
}
//功能:检查表格是否规整
//参数:tb--需要检查的表格ID
//data: 2011.11.06
function checkTable(tb){
if(tb.rows.length==0) return false
if(tb.rows[0].cells.length==0) return false
for(var i=0i<tb.rows.lengthi++){
if(tb.rows[0].cells.length!=tb.rows[i].cells.length) return false
}
return true
}
</script>
</head>
<body>
<table width="400" border="1" id="table1">
<tr>
<td>a</td>
<td>for</td>
<td>100</td>
<td>200</td>
<td>1</td>
</tr>
<tr>
<td>a</td>
<td>for</td>
<td>100</td>
<td>300</td>
<td>2</td>
</tr>
<tr>
<td>a</td>
<td>if</td>
<td>100</td>
<td>200</td>
<td>3</td>
</tr>
<tr>
<td>a</td>
<td>if</td>
<td>300</td>
<td>230</td>
<td>4</td>
</tr>
<tr>
<td>a</td>
<td>if</td>
<td>320</td>
<td>230</td>
<td>5</td>
</tr>
</table>
<br><input type="button" value="合并表格" onClick="uniteTable(table1,4)">
</body>
</html>