我使用rowReordering插件jQuery DataTables让用户拖放行。以下是相关代码:
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。
这种行为是不可取的。如何确保行索引正在更新?
发布于 2015-08-16 14:14:02
致
行索引0
用作row-selector
for row()
API方法是在初始化期间分配的内部索引,不代表项的位置,有关更多信息,请参见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>
https://stackoverflow.com/questions/32024350
复制相似问题