[JS] DataTable 에러 및 설정

alirz-pixel·2022년 8월 10일

HTML

목록 보기
1/1

사용

DataTable을 사용하기 위해선 아래의 링크를 import 시켜주면 된다.

<!-- 데이터테이블 -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>

추가 기능

column에 a tag 추가하기

$('<TAGID>').DataTable({
  columns: [
    { data : 'value',
     /*
      * value가 아닌 다른 column의 값을 다루고 싶다면,
      * row[<COLUMN명>]으로 사용하면 된다.
      */
      "render" : function (data, type, row) {
          return '<a href="' + data + '">' + data + '</a>';
      }
  ]
});

특정 열 sort 기능 끄기

  1. html의 th에 data-orderable="false" 추가하기
<th data-orderable="false"></th>
  1. js의 DataTable에 속성 추가하기
, columnDefs: [{ "targets": [0], "orderable": false }]

너비 자동맞춤 끄기

DataTable에 bAutoWidth: false 을 추가해주면 된다.
추가적으로 너비를 고정하고 싶다면, 아래와 같이 사용하면 된다.

, bAutoWidth: false
, columnDefs: [
    { width: "10%", targets : 0 },
    { width: "10%", targets: 1 },
    { width: "20%", targets: 2 },
    { width: "10%", targets: 3 },
    { width: "8%", targets: 4 },
    { width: "10%", targets: 5 },
    { width: "45%", targets: 6 }
 ],
  

에러 목록

Cannot reinitalise DataTable

DataTables warning: table id=materialModalTbl -Cannot reinitialise DataTable. 
For more information about this error, please see http://datatables.net/tn/3

해당 에러는 위와 같은 alert와 함께 뜨게 되는데,
ID가 materialModalTbl 인 datatables를 재정의 할 수 없다 라는 뜻이다.
(이미 초기화 된 DataTable을 한 번 더 초기화 하기 때문)

해결법

  • DataTable 을 1번만 초기화하도록 변경한다.
  • DataTable 속성에 destory: true를 추가해주면 된다.
$('<TAGID>').DataTable({
  ...
  destory: true,
  ...
});
  • DataTable 이 초기화 되어있다면, detory를 호출해도 된다.
    if ( $.fn.DataTable.isDataTable( '#materialModalTbl' ) ) {
    	$('#materialModalTbl').DataTable().destroy();
    }

Datatables Cannot read properties of undefined

해당 오류는 thead, tbody 태그가 없거나,
trtd의 갯수가 일치자히 않을 때 발생하게 된다.


reference

0개의 댓글