簡體   English   中英

jQuery數據表:選擇擴展:如何在init上選擇第一行以及如何至少選擇一行

[英]jquery datatables: Select Extension: How to select first row on init and how to get at least one row selected

我對jquery數據表有兩個問題:

  1. 初始化DataTable后,是否可以自動選擇第一行?
  2. 目前,用戶有可能通過單擊來取消選擇項目。 我想要至少選擇一行。 當用戶單擊到選定的行時,不應刪除選擇。

這是我對DataTable的初始化:

ar dataTableOption = {"pageLength": 5,
    "pagingType": "simple",
    "info": false,
    "searching": false,
    "select": {
        style: 'single'
    },
    "lengthChange": false,
    "columnDefs": [
        {
            "targets": [0],
            "visible": false,
            "searchable": false
        }
    ]
};

dataTable = $('#dataTable').DataTable(dataTableOption);

提前謝謝你的幫助!

方式之一:

$(document).ready(function() {
    var table = $('#example').DataTable(); 

    $('#example tbody').on( 'click', 'tr', function () {

        if($(this).hasClass( "selected" )){
          //make sure it can't be unselected if there is just one selected row
          if(table.rows('.selected').data().length > 1){
            $(this).removeClass( "selected" );}
        }
        else{
         $(this).addClass( "selected" );
        }
    } );

    //To pre-select the first row
    $('#example tbody tr:eq(0)').click();
} );

演示版

@ Harshul Pandav

謝謝你的文章。 您提出的解決方案對我來說不是100%有效,但是它為我的問題找到了解決方案,對我很有幫助。

選擇第一行對我來說是可行的:

dataTable.row(':eq(0)', { page: 'current' }).select();

要選擇至少一行,我使用用戶選擇事件,以記住我上次選擇的列:

dataTable.on( 'user-select', function ( e, dt, type, indexes ) {
      lastSelectedRow = dt.rows( '.selected' )[0][0];
    });

此后,單擊事件將通過,如果不再選擇任何行,則選擇具有最后選擇的行的索引的行:

 dataTable.on( 'click', 'tr', function (evt) { 
if (dataTable.rows( {selected:true} ).any() == false) {
     dataTable.row(lastSelectedRow).select();
  }
)};

為了找出最后選擇的行,還可以使用deselect(dt.on('deselect',function(e,dt,type,index)))事件。

防止取消選擇已選擇的行:

    myTable.on('user-select', function (e, dt, type, cell, originalEvent) {
        if ($(cell.node()).parent().hasClass('selected')) {
            e.preventDefault();
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM