Skip to content

Instantly share code, notes, and snippets.

@namkyu
Created November 7, 2012 11:21
Show Gist options
  • Save namkyu/4030935 to your computer and use it in GitHub Desktop.
Save namkyu/4030935 to your computer and use it in GitHub Desktop.
table cell merge
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// cell merge
mergeCell("listTable");
});
// cell merge
function mergeCell(tableId) {
// variable 정의
var first = true;
var prevRowspan1 = 1;
var prevCell1 = null;
var prevRowspan2 = 1;
var prevCell2 = null;
// tr 모두 추출
var rows = $("#" + tableId + " > tbody").children();
for (var i = 0; i < rows.length; i++ ) {
// first row
if (first) {
prevRow = rows[i];
prevCell1 = $(prevRow).find("td").eq(0); // 기간
prevCell2 = $(prevRow).find("td").eq(1); // 성별
console.log("#############################################");
console.log("## first row process");
console.log("#############################################");
console.log(prevCell1);
console.log(prevCell2);
first = false;
continue;
}
var row = rows[i]; // row
var tdList = $(row).find("td"); // row > td 리스트
var firstCell = $(tdList).eq(0); // 첫 번째 행
var secondCell = $(tdList).eq(1); // 두 번째 행
var firstCellText = $(firstCell).text(); // 첫 번째 행 text 추출
var secondCellText = $(secondCell).text() // 두 번째 행 text 추출
// 두 번째 row 부터 텍스트 비교
if (prevCell1.text() == firstCellText) {
if (prevCell2.text() == secondCellText) { // 성별 값 비교
prevRowspan2++; // 중복되는 값이 있으므로 rowspan +1
$(prevCell2).attr("rowspan", prevRowspan2); // 첫 번째 row의 두 번째 cell에 rowspan 추가 (성별)
$(secondCell).remove(); // 중복 cell element 삭제
} else {
prevRowspan2 = 1;
prevCell2 = secondCell;
}
prevRowspan1++;
$(prevCell1).attr("rowspan", prevRowspan1);
$(firstCell).remove();
}
else {
prevRowspan1 = 1;
prevRowspan2 = 1;
prevCell1 = firstCell;
prevCell2 = secondCell;
}
}
}
</script>
</head>
<body>
<table id="listTable" border="1">
<thead>
<tr>
<th>기간</th>
<th>성별</th>
<th>연령</th>
<th>접속count</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012.11.06</td>
<td>남자</td>
<td>14</td>
<td>200</td>
</tr>
<tr>
<td>2012.11.06</td>
<td>남자</td>
<td>15</td>
<td>200</td>
</tr>
<tr>
<td>2012.11.07</td>
<td>남자</td>
<td>16</td>
<td>200</td>
</tr>
<tr>
<td>2012.11.06</td>
<td>남자</td>
<td>17</td>
<td>200</td>
</tr>
<tr>
<td>2012.11.06</td>
<td>여자</td>
<td>14</td>
<td>200</td>
</tr>
<tr>
<td>2012.11.06</td>
<td>여자</td>
<td>15</td>
<td>400</td>
</tr>
<tr>
<td>2012.11.07</td>
<td>여자</td>
<td>15</td>
<td>400</td>
</tr>
</tbody>
</table>
</body>
</html>
@namkyu
Copy link
Author

namkyu commented Nov 7, 2012

HTML 테이블의 cell 머지하는 방법

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment