티스토리 뷰

반응형

JQuery로 table 값 변경하고 텍스트 말줄임처리



먼저 아래 jquery 스크립트 부분을 페이지에 넣는다.

1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js";></script>
cs



jquery 부분


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$(function() {
    var tr_length = $('#tb tr').length-1;//맨위 테이블 행은 빼줘야한다.
    var tab_td = $('#tb td');//tb 테이블의 td들 불러오기
    var text = "...";//말 줄임표
    for (var i = 0; i < tr_length; i++) {
        if(i==0){
            var td1 = tab_td.eq(i).text();
            if(td1.length>20){//35글자가 넘으면
                $("#tb td:eq("+i+")").html(td1.substr(0,20)+text);
            }
        }else{
            var td2 = tab_td.eq(i*2).text();//tr 안에 td 들이 2개라서 곱하기 2
            if(td2.length>20){//35글자가 넘으면
                $("#tb td:eq("+(i*2)+")").html(td2.substr(0,20)+text);
            }
        }
    }
});
cs





html 부분


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    <table id="tb" name="tb">
        <tbody>
            <tr>
                <th>text</th>
                <th>date</th>
            </tr>
            <tr>
                <td>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</td>
                <td>2018-11-14</td>
            </tr>
            <tr>
                <td>bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb</td>
                <td>2018-11-14</td>
            </tr>
            <tr>
                <td>ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc</td>
                <td>2018-11-14</td>
            </tr>
            <tr>
                <td>ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd</td>
                <td>2018-11-14</td>
            </tr>
        </tbody>
    </table>
cs





완성 모습



반응형
댓글
공지사항