添加一行时,jQuery 数据表滚动到底部

use*_*713 3 html javascript jquery scroll datatables

每当添加一行时,我希望我的 DataTable 滚动到底部。我已经针对这个问题尝试了多种修复方法,但都没有奏效。

经测试的解决方案:

其中...

我认为,从别人我的情况下分开,是我用DataTableD大写。

无论如何,这是我当前的代码:

var table = $('#example').DataTable({
          "createdRow": function( row, data, dataIndex ) 
          {
             $(row).attr('id', 'row-' + dataIndex);
          },
          "bPaginate": false,
        "bLengthChange": false,
        "bFilter": false,
        "bInfo": false,
        "bAutoWidth": false,
        "scrollY":        $(window).height()/1.5,
        "scrollCollapse": true,
        "paging":         false,
   });

   for(var i = 1; i <= 20; i++){
      table.row.add([ 
         i,
         'action'+i,
      ]);
   }  

   table.draw();

   table.rowReordering();
Run Code Online (Sandbox Code Playgroud)

如果表格在添加新行时滚动到底部,那就太好了。

Gyr*_*com 9

解决方案

要滚动到表格底部,请使用以下代码:

var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
Run Code Online (Sandbox Code Playgroud)

演示

var $scrollBody = $(table.table().node()).parent();
$scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
Run Code Online (Sandbox Code Playgroud)
$(document).ready( function () {
   var table = $('#example').DataTable({
      "createdRow": function( row, data, dataIndex ) {
         $(row).attr('id', 'row-' + dataIndex);
        console.log($(row).closest('table').parent());
      },
      "scrollY":        $(window).height()/1.5,
      "scrollCollapse": true,
      "paging": false
   });

   $('#btn-add').click(function(){    
      for(var i = 1; i <= 10; i++){
         table.row.add([ 
            i,
            i + '.2',
            i + '.3',
            i + '.4',
            i + '.5',
            i + '.6'
         ]);
      }  
   
      table.draw();      

      // Scroll to the bottom
      var $scrollBody = $(table.table().node()).parent();
      $scrollBody.scrollTop($scrollBody.get(0).scrollHeight);
   });
  
   table.rowReordering();
} );
Run Code Online (Sandbox Code Playgroud)