JavaScript合并table相同内容的单元格
程序员文章站
2024-02-28 17:40:34
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript合并table相同内容的单元格</title>
</head>
<body>
<style type="text/css">
textarea{
height: 400px;
}
table
{
border-collapse: collapse;
margin: 0 auto;
text-align: center;
}
table td, table th
{
border: 1px solid #666666;
}
</style>
<script>
/
//功能:合并表格
//参数:tb-需要合并的表格ID
//参数:colLength--需要对前几列进行合并,比如,
//想合并前两列,后面的数据列忽略合并,colLength应为2
//缺省表示对全部列合并
///
function mergeTableCell(tb, colLength) {
tb = document.getElementById(tb);
//检查表格是否规整
if (!checkTableRegular(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 = 0; i < rowCount; i++) {
for (j = 0; j < colCount; j++) {
tb.rows[i].cells[j].id = 'tb__' + i.toString() + '_' + j.toString();
}
}
//逐列检查合并
for (i = 0; i < colCount; i++) {
if (i == colLength) return;
obj1 = document.getElementById('tb__0_' + i.toString());
for (j = 1; j < rowCount; j++) {
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--需要检查的table
/
function checkTableRegular(tb) {
if (tb.rows.length == 0) return false;
if (tb.rows[0].cells.length == 0) return false;
for (var i = 0; i < tb.rows.length; i++) {
if (tb.rows[0].cells.length != tb.rows[i].cells.length) return false;
}
return true;
}
</script>
<table id="table1">
<tr>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>1</td>
</tr>
<tr>
<td>A1</td>
<td>B1</td>
<td>C2</td>
<td>2</td>
</tr>
<tr>
<td>A1</td>
<td>B2</td>
<td>C3</td>
<td>4</td>
</tr>
<tr>
<td>A1</td>
<td>B2</td>
<td>C4</td>
<td>4</td>
</tr>
</table>
<br>
<input type="button" value="合并相同内容的单元格" onclick="mergeTableCell('table1')">
</body>
</html>
上一篇: Spring rest对etag支持
下一篇: webView网络缓存1 - ETag
推荐阅读
-
javascript根据单元格内容动态合并相同内容单元格
-
JavaScript合并table相同内容的单元格
-
JavaScript+CSS2+DIV+Table单击Table的单元格(td)弹出层可以修改单元格 JavaScriptCC++C#
-
java导出excel时合并同一列中相同内容的行
-
jquery 合并内容相同的单元格(示例代码)_jquery
-
phpexcel 如何向合并的单元格写内容
-
phpexcel 怎么向合并的单元格写内容
-
Js 导出table内容到Excel的简单实例_javascript技巧
-
javascript实现的使用方向键控制光标在table单元格中切换_javascript技巧
-
jquery 合并内容相同的单元格(示例代码)_jquery