Jquery dynamic table 생성시 문제점 해결

이기현·2020년 12월 23일

Spring Boot

목록 보기
10/12

기존의 dynamic하게 table생성하는 방식은

$(".userInfo").find('tbody').append("<tr>")
$(".userInfo").find('tbody').append("<td> <input class=\"listCheck\" type=\"checkbox\" value='" + num + "'></td>");
$(".userInfo").find('tbody').append("<td>" + num +  "</td>");
$(".userInfo").find('tbody').append("<td>" + data[count].name +  "</td>");
$(".userInfo").find('tbody').append("<td>" + data[count].position +  "</td>");
$(".userInfo").find('tbody').append("<td>" + data[count].company +  "</td>");
$(".userInfo").find('tbody').append("<td>" + data[count].department +  "</td>");
$(".userInfo").find('tbody').append("<td>" + data[count].duty +  "</td>");
$(".userInfo").find('tbody').append("<td>" + data[count].email +  "</td>");

으로 하였다.
하지만 해당 방식으로 table생성시

<tr></tr>
<td>...<td>

식으로 tr안에 td가 감싸져있지 못하는 문제점이 발생한다.

따라서 해결방법으로는

$("#tableID").find('tbody')
    .append($('<tr>')
        .append($('<td>')
            .append($('<img>')
                .attr('src', 'img.png')
                .text('Image cell')
            )
        )
    );

The $('') thing in jQuery is a tag object that can have several attr attributes that can be set and get, as well as text, which represents the text between the tag here: text.

이 있다.

즉 위의 코드를 변경하면

$(".userInfo").find('tbody').append($("<tr>")
    .append("<td> <input class=\"listCheck\" type=\"checkbox\" value='" + num + "'></td>")
    .append("<td>" + num +  "</td>")
    .append("<td>" + data[count].name +  "</td>")
    .append("<td>" + data[count].position +  "</td>")
    .append("<td>" + data[count].company +  "</td>")
    .append("<td>" + data[count].department +  "</td>")
    .append("<td>" + data[count].duty +  "</td>")
    .append("<td>" + data[count].email +  "</td>"));

로 해주면 tr안에 td가 감싸져 있는것을 확인할 수 있다.

참고 : https://stackoverflow.com/questions/171027/add-table-row-in-jquery

profile
실력을 쌓아가는 하루하루

0개의 댓글