programing tip

jQuery DataTables에서 특정 열에 대한 정렬 비활성화

itbloger 2020. 6. 9. 08:23
반응형

jQuery DataTables에서 특정 열에 대한 정렬 비활성화


jQuery DataTables 플러그인사용 하여 테이블 필드를 정렬하고 있습니다. 내 질문은 : 특정 열에 대한 정렬을 어떻게 비활성화합니까? 다음 코드로 시도했지만 작동하지 않았습니다.

"aoColumns": [
  { "bSearchable": false },
  null
]   

또한 다음 코드를 시도했습니다.

"aoColumnDefs": [
  {
    "bSearchable": false,
    "aTargets": [ 1 ]
  }
]

그러나 여전히 원하는 결과를 얻지 못했습니다.


이것은 당신이 찾고있는 것입니다 :

$('#example').dataTable( {
      "aoColumnDefs": [
          { 'bSortable': false, 'aTargets': [ 1 ] }
       ]
});

DataTables 1.10.5부터 HTML5 data- * 속성을 사용하여 초기화 옵션을 정의 할 수 있습니다.

-fromDataTables 예제 -HTML5 data- * 속성-테이블 옵션

당신이 사용할 수 있도록 data-orderable="false"th열 당신이 정렬되고 싶지 않아. 예를 들어 아래 표의 두 번째 열 "아바타"는 정렬 할 수 없습니다.

<table id="example" class="display" width="100%" data-page-length="25">
    <thead>
        <tr>
            <th>Name</th>
            <th data-orderable="false">Avatar</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td><img src="https://www.gravatar.com/avatar/8edcff60cdcca2ad650758fa524d4990?s=64&amp;d=identicon&amp;r=PG" alt="" style="width: 64px; height: 64px; visibility: visible;"></td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td>Garrett Winters</td>
            <td><img src="https://www.gravatar.com/avatar/98fe9834dcca2ad650758fa524d4990?s=64&amp;d=identicon&amp;r=PG" alt="" style="width: 64px; height: 64px; visibility: visible;"></td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>
        ...[ETC]...
    </tbody>
</table>

참조 https://jsfiddle.net/jhfrench/6yxvxt7L/에서 동작하는 예제를 .


첫 번째 열 정렬을 비활성화하려면 datatables jquery에서 아래 코드를 사용해보십시오. 널은 여기서 정렬 가능을 나타냅니다.

$('#example').dataTable( {
  "aoColumns": [
  { "bSortable": false },
  null,
  null,
  null
  ]
} );

jQuery 데이터 테이블에서 열 정렬 비활성화


Datatables 1.9.4 사용이 코드로 첫 번째 열의 정렬을 비활성화했습니다.

/* Table initialisation */
$(document).ready(function() {
    $('#rules').dataTable({
        "sDom" : "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>",
        "sPaginationType" : "bootstrap",
        "oLanguage" : {
            "sLengthMenu" : "_MENU_ records per page"
        },
        // Disable sorting on the first column
        "aoColumnDefs" : [ {
            'bSortable' : false,
            'aTargets' : [ 0 ]
        } ]
    });
});

편집하다:

no-sort클래스를 사용하여 사용 중지 할 수도 있습니다 <th>.

이 초기화 코드를 사용하십시오.

// Disable sorting on the no-sort class
"aoColumnDefs" : [ {
    "bSortable" : false,
    "aTargets" : [ "no-sort" ]
} ]

편집 2

이 예에서는 이전 블로그 게시물에 따라 Bootstrap과 함께 Datables를 사용하고 있습니다. 이제 부트 스트랩을 사용하여 데이터 테이블 스타일링 에 대한 업데이트 된 자료가 포함 된 하나의 링크가 있습니다.


내가 사용하는 것은 ad td에 사용자 정의 속성을 추가하고 해당 attr 값을 자동으로 확인하여 정렬을 제어하는 ​​것입니다.

HTML 코드는

<table class="datatables" cellspacing="0px" >

    <thead>
        <tr>
            <td data-bSortable="true">Requirements</td>
            <td>Test Cases</td>
            <td data-bSortable="true">Automated</td>
            <td>Created On</td>
            <td>Automated Status</td>
            <td>Tags</td>
            <td>Action</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>

데이터 테이블을 초기화하는 JavaScript는 (테이블 자체에서 정렬 정보를 동적으로 가져옵니다.)

$('.datatables').each(function(){
    var bFilter = true;
    if($(this).hasClass('nofilter')){
        bFilter = false;
    }
    var columnSort = new Array; 
    $(this).find('thead tr td').each(function(){
        if($(this).attr('data-bSortable') == 'true') {
            columnSort.push({ "bSortable": true });
        } else {
            columnSort.push({ "bSortable": false });
        }
    });
    $(this).dataTable({
        "sPaginationType": "full_numbers",
        "bFilter": bFilter,
        "fnDrawCallback": function( oSettings ) {
        },
        "aoColumns": columnSort
    });
});

columnDefs이제 수업을받습니다. 마크 업에서 비활성화 할 열을 지정하려는 경우 이것이 선호되는 방법이라고 말하고 싶습니다.

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th class="datatable-nosort">Actions</th>
        </tr>
    </thead>
    ...
</table>

그런 다음 JS에서 :

$("table").DataTable({
    columnDefs: [{
        targets: "datatable-nosort",
        orderable: false
    }]
});

특정 열을 비활성화 할 수있는 기능은 다음과 같습니다.

 $('#tableId').dataTable({           
            "columns": [
                { "data": "id"},
                { "data": "sampleSortableColumn" },
                { "data": "otherSortableColumn" },
                { "data": "unsortableColumn", "orderable": false}
           ]
});

따라서 정렬 할 수없는 열에 "orderable": false를 추가하기 만하면됩니다.


$("#example").dataTable(
  {
    "aoColumnDefs": [{
      "bSortable": false, 
      "aTargets": [0, 1, 2, 3, 4, 5]
    }]
  }
);

단일 열 정렬을 비활성화하려면 다음 예제를 시도하십시오.

<script type="text/javascript">                         
    $(document).ready(function() 
    {
        $("#example").dataTable({
           "aoColumnDefs": [
              { 'bSortable': false, 'aTargets': [ 0 ] }
           ]
        });
    });                                         
</script>

여러 열의 경우이 예제를 시도하십시오. 열 번호 만 추가하면됩니다. 기본적으로 0부터 시작합니다

<script type="text/javascript">                         
    $(document).ready(function() 
    {
        $("#example").dataTable({
           "aoColumnDefs": [
              { 'bSortable': false, 'aTargets': [ 0,1,2,4,5,6] }
           ]
        });
    });                                         
</script>  

여기서 만 Column 3작동


1.10.5 기준으로 간단히 포함

'주문 가능 : 거짓'

columnDefs에서

'대상 : [0,1]'

테이블은 다음과 같아야합니다.

var table = $('#data-tables').DataTable({
    columnDefs: [{
        targets: [0],
        orderable: false
    }]
});

FIRST column orderable속성을 false로 설정하면 기본 열도 설정 해야합니다.order 그렇지 않으면 첫 번째 열이 기본 순서 열이므로 작동하지 않습니다. 아래 예제는 첫 번째 열에서 정렬을 비활성화하지만 두 번째 열을 기본 순서 열로 설정합니다 (dataTables의 인덱스는 0을 기준으로합니다).

$('#example').dataTable( {
  "order": [[1, 'asc']],
  "columnDefs": [
    { "orderable": false, "targets": 0 }
  ]
} );

"aoColumnDefs" : [   
{
  'bSortable' : false,  
  'aTargets' : [ 0 ]
}]

다음 0은 열의 색인입니다. 여러 열을 정렬하지 않으려면 열 색인 값을comma(,)


Bhavish의 답변을 업데이트하려면 (이전 버전의 DataTables에 대한 것으로 생각되지 않습니다). 나는 그들이 속성 이름을 변경했다고 생각합니다. 이 시도:

<thead>
    <tr>
        <td data-sortable="false">Requirements</td>
        <td data-sortable="false">Automated</td>
        <td>Created On</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td>

수업 사용 :

<table  class="table table-datatable table-bordered" id="tableID">
    <thead>
        <tr>
            <th class="nosort"><input type="checkbox" id="checkAllreInvitation" /></th>
            <th class="sort-alpha">Employee name</th>
            <th class="sort-alpha">Send Date</th>
            <th class="sort-alpha">Sender</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" name="userUid[]" value="{user.uid}" id="checkAllreInvitation" class="checkItemre validate[required]" /></td>
            <td>Alexander Schwartz</td>
            <td>27.12.2015</td>
            <td>dummy@email.com</td>
        </tr>
    </tbody>
</table>
<script type="text/javascript">
    $(document).ready(function() {
        $('#tableID').DataTable({
            'iDisplayLength':100,
            "aaSorting": [[ 0, "asc" ]],
            'aoColumnDefs': [{
                'bSortable': false,
                'aTargets': ['nosort']
            }]
        });
    });
</script>

이제 "nosort"클래스를 <TH>에 제공 할 수 있습니다


이것은 하나의 열에 효과적입니다.

 $('#example').dataTable( {
"aoColumns": [
{ "bSortable": false 
 }]});

이미 성 열을 숨기는 것처럼 일부 열을 숨겨야하는 경우 방금 fname, lname을 연결해야 했으므로 쿼리를 만들었지 만 프런트 엔드에서 해당 열을 숨 깁니다. 이러한 상황에서 정렬 비활성화의 수정 사항은 다음과 같습니다.

    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ 3 ] },
        {
            "targets": [ 4 ],
            "visible": false,
            "searchable": true
        }
    ],

여기에 숨기기 기능이 있음에 유의하십시오.

    "columnDefs": [
            {
                "targets": [ 4 ],
                "visible": false,
                "searchable": true
            }
        ],

그런 다음에 병합했습니다. "aoColumnDefs"


  1. 첫 번째 열에서 순서를 비활성화하려면 다음 코드를 사용하십시오.

    $('#example').dataTable( {
      "columnDefs": [
        { "orderable": false, "targets": 0 }
      ]
    } );
    
  2. 기본 순서를 비활성화하려면 다음을 사용할 수도 있습니다.

    $('#example').dataTable( {
         "ordering": false, 
    } );
    

열에서 .notsortable () 메소드를 직접 사용할 수 있습니다

 vm.dtOpt_product = DTOptionsBuilder.newOptions()
                .withOption('responsive', true)
        vm.dtOpt_product.withPaginationType('full_numbers');
        vm.dtOpt_product.withColumnFilter({
            aoColumns: [{
                    type: 'null'
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'text',
                    bRegex: true,
                    bSmart: true
                }, {
                    type: 'select',
                    bRegex: false,
                    bSmart: true,
                    values: vm.dtProductTypes
                }]

        });

        vm.dtColDefs_product = [
            DTColumnDefBuilder.newColumnDef(0), DTColumnDefBuilder.newColumnDef(1),
            DTColumnDefBuilder.newColumnDef(2), DTColumnDefBuilder.newColumnDef(3).withClass('none'),
            DTColumnDefBuilder.newColumnDef(4), DTColumnDefBuilder.newColumnDef(5).notSortable()
        ];

테이블 헤더를 정의 할 때 html로 정의되는 두 가지 방법이 있습니다.

<thead>
  <th data-orderable="false"></th>
</thead>

또 다른 방법은 자바 스크립트를 사용하는 것입니다. 예를 들어 테이블이 있습니다.

<table id="datatables">
    <thead>
        <tr>
            <th class="testid input">test id</th>
            <th class="testname input">test name</th>
    </thead>
</table>

그때,

$(document).ready(function() {
    $('#datatables').DataTable( {
        "columnDefs": [ {
            "targets": [ 0], // 0 indicates the first column you define in <thead>
            "searchable": false
        }
        , {
            // you can also use name to get the target column
            "targets": 'testid', // name is the class you define in <th>
            "searchable": false
        }
        ]
    }
    );
}
);

음수 색인을 다음과 같이 사용할 수도 있습니다.

$('.datatable').dataTable({
    "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ -1 ] }
    ]
});

코드는 다음과 같습니다.

$(".data-cash").each(function (index) {
  $(this).dataTable({
    "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "oLanguage": {
      "sLengthMenu": "_MENU_ records per page",
      "oPaginate": {
        "sPrevious": "Prev",
        "sNext": "Next"
      }
    },
    "bSort": false,
    "aaSorting": []
  });
});

여기에 답이 있습니다!

targets 열 번호이며 0부터 시작합니다

$('#example').dataTable( {
  "columnDefs": [
    { "orderable": false, "targets": 0 }
  ]
} );

set class "no-sort" in th of the table then add css .no-sort { pointer-events: none !important; cursor: default !important;background-image: none !important; } by this it will hide the arrow updown and disble event in the head.

참고URL : https://stackoverflow.com/questions/3932587/disable-sorting-for-a-particular-column-in-jquery-datatables

반응형