jQuery DataTable 的行索引在交换两行后不更新(rowReordering 插件)

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

我正在使用 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()

将 return 来自当前索引 1 而非 0 的行数据。

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

CAUSE

行索引 0 用作 row-selector for row() API method is internal index that is assigned during initialization and doesn't represent position of the item, see row().index() 以获取更多信息。

SOLUTION

使用 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;

DEMO

$(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>