Daily Develope

[Web] Datatables 간단 예시 본문

Develope/Web

[Web] Datatables 간단 예시

noggame 2024. 9. 11. 15:08

환경설정

  1. datatables 다운로드 접속
  2. 원하는 환경 설정
  3. 하단의 JS 및 CSS 연결주소를 복사하거나, 해당 파일을 다운받아 삽입

(설치 후 사용하려는 경우 링크 참고)

사용 예시

HTML 파일

본 예시에서는 간단하게 헤더만 정의해두고 데이터는 JS에서 동적으로 처리

<table id="myTable" class="display">
    <thead>
        <tr>
            <th>index</th>
            <th>col_01</th>
            <th>col_02</th>
            <th>col_03</th>
        </tr>
    </thead>
</table>

JS 파일

테이블 초기화시 다양한 옵션을 사용해 쉽게 구성할 수 있다.
(사용 가능한 옵션은 Option 링크 참고.)

아래 코드는 앞서 선언한 table element에 DataTable 객체를 할당하는 방법으로 테이블 구성하는 예시이다.


var myData = [{"id":"id1", "user_name":"user01", "description":"des01"},{"id":"id2", "user_name":"user02", "description":"des02"}]

// myTable에 DataTable 객체를 할당하며, 초기화 과정에서 다양한 옵션을 지정할 수 있다.
var myTable = $('#myTable').DataTable({
    autoWidth: false,    // 테이블 가로 길이 자동 설정 여부
    language: {
        searchPlaceholder: "검색어",                // 검색창의 placeholder 값 지정
        zeroRecords : "검색된 데이터가 없습니다.",        // 검색 결과가 없는 경우 설정된 문자열 출력
        info :"Showing page _PAGE_ of _PAGES_",     // 테이블 요약 정보 출력
        loadingRecords:"Please wait",             // 테이블 로딩 중 출력 메시지
        processing:"DT is currently busy",         // 검색 중 출력 메시지
        lengthMenu: "Display _MENU_ records",     // 페이지 길이
    },
    columnDefs: [        // Column 속성 및 템플릿 정의
        {   // Column 0
            targets: 0,                    // target index
            className: "td-center",        // 지정된 class에 따라 디자인 적용
            width: '3%',                // 가로길이 비율로 설정
            orderable: false,            // 정렬 가능 여부
            render: function (data) {    // cell에 쓰여질 데이터 포맷 지정 (html tag 지정 가능)
                return '<div class="class01">data</div>';
            }
        },
        {   // Column 1
            targets: 1,
            width: '6%'
        },
        {   // Column 2
            targets: 2,
            className: "td-center",
            width: '5%',
            orderable: false,
            render: function (data, type, raw) {
                // data : 입력받은 맵핑된 데이터
                // type : 입력받은 데이터 타입
                // raw : 입력받은 데이터 전체

                return raw.id === 'id1' ? 'hello id1' : 'hello id2';
            }
        }
    ],
    columns:[
        {data: 'id'},
        {data: 'user_name'},
        {data: 'description'}
    ],
    order: {
        // user_name 기준으로 내림차순 정렬
        name: 'user_name',
        dir: 'desc'
    },
    data: myData
});

'Develope > Web' 카테고리의 다른 글

[JS] javascript 예시 코드 모음  (0) 2024.09.02
[CSS] 작성 규칙  (0) 2024.05.02
[SSL] NginX SSL 인증서 설정  (0) 2023.08.17
[WEB] 동적 웹페이지 처리 with Python  (0) 2023.05.09
[Web] XPath 간단 정리  (0) 2023.05.09
Comments