개발이야기/자바스크립트

[자바스크립트] javascript 테이블 병합하기 (table td rowspan)

후린개발자 2022. 10. 13.
반응형

table td text에 class명이 동일한 값이 위아래로 있을 경우 병합해주는 함수입니다.
tbody의 병합할 컬럼 번호를 호출해서 값을 비교하고 있습니다.
저는 시군구 컬럼과 읍면동 컬럼을 병합하고 있습니다.

아래 예제를 통해서 다양하게 응용하시면 될 것 같습니다.

 

병합 하기 이전의 table data

<style>
 table {
    width: 100%;
    border: 1px solid #444444;
  }
  th, td {
    border: 1px solid #444444;
	text-align: center;
  }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<button type="button" onclick="merge();" style="border-style:solid;">병합하기</button>
<table>
<thead>
	<tr>
		<th>순번</th>
		<th>이름</th>
		<th>시군구</th>
		<th>읍면동</th>
	</tr>
</thead>
<tbody class="infoTbody">
	<tr>
		<td>1</td>
		<td>홍길동</td>
		<td class='seoul'>서울특별시</td>
		<td class='seocho'>서초구</td>
	</tr>
	<tr>
		<td>2</td>
		<td>이순신</td>
		<td class='seoul'>서울특별시</td>
		<td class='gangnam'>강남구</td>
	</tr>
	<tr>
		<td>3</td>
		<td>심봉사</td>
		<td class='gyeonggi'>겅기도</td>
		<td class='bucheon'>부천시</td>
	</tr>
	<tr>
		<td>4</td>
		<td>심청이</td>
		<td class='gyeonggi'>경기도</td>
		<td class='bucheon'>부천시</td>
	</tr>
	<tr>
		<td>5</td>
		<td>유관순</td>
		<td class='seoul'>서울특별시</td>
		<td class='yeongdeungpo'>영등포구</td>
	</tr>

</tbody>
</table>

<script> 
$.fn.mergeRowspan = function (colIdx) {
    return this.each(function () {
        var that;
        $('tr', this).each(function (row) {
            $('td:eq(' + colIdx + ')', this).filter(':visible').each(function (col) {
                if ($(this).attr('class') == $(that).attr('class')) {
                    rowspan = $(that).attr("rowspan") || 1;
                    rowspan = Number(rowspan) + 1;
                    $(that).attr("rowspan", rowspan);
                    $(this).hide();
                } else {
                    that = this;
                }
                that = (that == null) ? this : that;
            });
        });
    });
};
function merge(){
    $('.infoTbody').mergeRowspan(2);
    $('.infoTbody').mergeRowspan(3);
}
</script>

 

↓↓↓↓↓ 결과화면

병합 후 table data

 

반응형

댓글

💲 추천 글