方法一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body> <table id="table1">
<tr>
<td>111</td>
<td>222</td>
<td>333</td>
</tr>
<tr>
<td>111</td>
<td>555</td>
<td>333</td>
</tr>
<tr>
<td>111</td>
<td>888</td>
<td>333</td>
</tr>
<tr>
<td>aaa</td>
<td>bbb</td>
<td>333</td>
</tr>
</table> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script> jQuery.fn.rowspan = function(colIdx) { //封装的一个JQuery小插件
return this.each(function(){
var that;
$('tr', this).each(function(row) {
$('td:eq('+colIdx+')', this).filter(':visible').each(function(col) {
if (that!=null && $(this).html() == $(that).html()) {
rowspan = $(that).attr("rowSpan");
if (rowspan == undefined) {
$(that).attr("rowSpan",1);
rowspan = $(that).attr("rowSpan"); }
rowspan = Number(rowspan)+1;
$(that).attr("rowSpan",rowspan);
$(this).hide();
} else {
that = this;
}
});
});
});
}
$(function() {
$("#table1").rowspan(0);//传入的参数是对应的列数从0开始 第一列合并相同
// $("#table1").rowspan(1);//传入的参数是对应的列数从0开始 第二列合并相同
});
</script> </script>
</html>
合并前:
合并后:(根据实际项目需求,只合并第一列)
方法二:
function hb() {
var tab = document.getElementById("subtable");
var maxCol = 3, val, count, start;
var ys = "";
for (var col = maxCol - 1; col >= 0 ; col--) {
count = 1;
val = "";
for (var i = 0; i < tab.rows.length; i++) {
if (val == tab.rows[i].cells[col].innerHTML) {
count++;
} else {
if (count > 1) {
//合并
start = i - count;
if (ys == "#00FFFF") {
ys = "#EEEE00";
} else {
ys = "#00FFFF";
}
tab.rows[start].cells[col].rowSpan = count;
tab.rows[start].cells[1].style.backgroundColor = ys;//改变颜色
// ys="#EEEE00";
// tab.rows[i].cells[1].style.backgroundColor="#00FFFF";//改变颜色绿色
for (var j = start + 1; j < i; j++) { //
tab.rows[j].cells[col].style.display = "none";
tab.rows[j].removeChild(tab.rows[j].cells[col]);
}
count = 1;
}
val = tab.rows[i].cells[col].innerHTML;
}
} if (count > 1) { //合并,最后几行相同的情况下
start = i - count;
tab.rows[start].cells[col].rowSpan = count;
for (var j = start + 1; j < i; j++) {
tab.rows[j].removeChild(tab.rows[j].cells[col]);
}
}
}
}
第一种方法,仅用20行代码就可实现该功能,而且封装在jq库里面,其他页面可以直接调用。
第二种方法比较复杂,而且会把tabel里面所有相同列都合并,不实用。但是思路可以学习一下。