냐냐한 IT/냐냐한 JavaScript

javascript(jquery)로 table 행 병합(rowspan)

소소하냐 2019. 11. 1. 12:33

예전에 작업했던 내용들을 기억/기록하기 위해 남기는 포스팅입니다. 

 

테이블 형태의 데이터를 가져와서 동일한 내용의 행을 병합하는 작업을 서버단에서 하지 않고 JavaScript를 이용하면 조금 더 편해진다.

 

JavaScript 코드

  
  $.fn.mergeClassRowspan = 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);

                    // do your action for the colspan cell here            
                    $(this).hide();

                    //$(this).remove(); 
                    // do your action for the old cell here

                } else {
                    that = this;
                }

                // set the that if not already set
                that = (that == null) ? this : that;
            });
        });
    });
};

$(function(){
  $('table tbody').mergeClassRowspan(1);
  $('table tbody').mergeClassRowspan(2);
});

 

Html 코드 (사용)

<html>
<head>
</head>
<body>

  <table border="1">
    <thead>
    <tr>
      <th>번호</th>
      <th>학년</th>
      <th>과목</th>
      <th>교재</th>
    </tr>
    </thead>
    <tbody>
    <tr>
      <td>1</td>
      <td class="grade_1">1학년</td>
      <td class="sub_ko">국어</td>
      <td>국어교재1</td>      
    </tr>
    <tr>
      <td>1</td>
      <td class="grade_1">1학년</td>
      <td class="sub_ko">국어</td>
      <td>국어교재2</td>      
    </tr>
    <tr>
      <td>1</td>
      <td class="grade_1">1학년</td>
      <td class="sub_en">영어</td>
      <td>영어교재1</td>      
    </tr>
    <tr>
      <td>1</td>
      <td class="grade_1">1학년</td>
      <td class="sub_so">사회</td>
      <td>사회교재1</td>      
    </tr>
    <tr>
      <td>1</td>
      <td class="grade_2">2학년</td>
      <td class="sub_ko">국어</td>
      <td>국어교재1</td>      
    </tr>
    <tr>
      <td>1</td>
      <td class="grade_2">2학년</td>
      <td class="sub_en">영어</td>
      <td>영어교재1</td>      
    </tr>
    </tbody>
  </table>

</body>
</html>

 

결과 화면

결과 화면

 

JSFiddle에서 확인하기 [새창]