jQuery DataTable's的行索引在交换了两行之后不会更新(rowReordering插件)

jQuery DataTable's row indexes are not updated after two rows have been swapped (rowReordering plugin)

本文关键字:之后 两行 插件 rowReordering 更新 交换 DataTable jQuery 索引      更新时间:2023-09-26

我正在使用jQuery DataTables的rowReordering插件来让用户拖放行。以下是相关代码:

    ui_actions = $('#ui_actions').DataTable({
          "createdRow": function( row, data, dataIndex ) 
          {
             $(row).attr('id', 'row-' + dataIndex);
             ui_actions.$('tr.selected').removeClass('selected');
              $(row).addClass('selected');
          },
   });
   ui_actions.draw();
   ui_actions.rowReordering({
        fnUpdateCallback: function(row){
          ...
        }
   });

如果交换了两行(让我们考虑那些索引为1和2的行(,那么这行代码:

ui_actions.row(0).data()

将返回当前位于索引1而非0的行数据。

这种行为是不可取的。如何确保行索引正在更新?

原因

行索引0用作row() API方法的row-selector,是在初始化期间分配的内部索引,不表示项的位置,有关详细信息,请参阅row().index()

解决方案

使用jQuery选择器作为row() API方法访问第一行数据的参数:

var rowdata = ui_actions.row('tr:eq(0)').data();

或者使用rows() API方法访问第一行的数据:

var data = ui_actions.rows().data();
var rowdata = (data.length) ? data[0] : null;

演示

$(document).ready( function () {
   var table = $('#example').DataTable({
      "createdRow": function( row, data, dataIndex ) {
         $(row).attr('id', 'row-' + dataIndex);
      }    
   });
   for(var i = 1; i <= 100; i++){
      table.row.add([ 
         i,
         i + '.2',
         i + '.3',
         i + '.4',
         i + '.5',
         i + '.6'
      ]);
   }  
   table.draw();
   table.rowReordering();
  
   $('#btn-log').on('click', function(){
      var rowdata = table.row('tr:eq(0)').data();
      console.log('Method 1', rowdata);
     
      var data = table.rows().data();
      rowdata = (data.length) ? data[0] : null;
      console.log('Method 2', rowdata);
   });
} );
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>jQuery DataTables</title>  
<link href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/mpryvkin/jquery-datatables-row-reordering/95b44786cb41cf37bd3ad39e39e1d216277bd727/media/js/jquery.dataTables.rowReordering.js"></script>
</head>
  
<body>
<p><button id="btn-log" type="button">Log</button>
<table id="example" class="display" width="100%">
<thead>
<tr>
  <th>Name</th>
  <th>Position</th>
  <th>Office</th>
  <th>Age</th>
  <th>Start date</th>
  <th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
  <th>Name</th>
  <th>Position</th>
  <th>Office</th>
  <th>Age</th>
  <th>Start date</th>
  <th>Salary</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</body>
</html>