我尝试在数据表中的顶部和底部箭头交换jquery中的数据表行。
关注我的javascript代码示例:
$('#example tbody').on('click', '.swapDown', function(event) {
var _this = $(this),
ind = table.row(_this.closest("tr")).index();
var movedData = table.row(_this.closest("tr")).data(),
otherData = table.row(_this.closest("tr").next()).data();
console.log(movedData);
console.log(otherData);
table.row(_this.closest("tr").next()).data(movedData).draw(false);
table.row(_this.closest("tr")).data(otherData).draw(false);
console.log(_this.closest("tr").next());
console.log(_this.closest("tr"));
});
$('#example tbody').on('click', '.swapUp', function(event) {
var _this = $(this),
ind = table.row(_this.closest("tr")).index();
console.log(ind)
if(ind > 0){
var movedData = table.row(_this.closest("tr")).data(),
otherData = table.row(_this.closest("tr").prev()).data();
table.row(_this.closest("tr").prev()).data(movedData).draw(false);
table.row(_this.closest("tr")).data(otherData).draw(false);
}
});
});
答案 0 :(得分:0)
请注意DataTable现在提供非编辑器表格。有关详细信息,请参阅https://datatables.net/extensions/rowreorder/examples/initialisation/simple.html。
自定义交换工具:
JavaScript的:
$(document).ready(function() {
// get the table and table body
var $elm = $('#myTable'),
$bdy = $elm.find('tbody > tr');
// add the swap controls to table
$bdy.each(function() {
$(this).append('<span class="swap"><i class="up"></i><i class="down"></i></span>');
});
// initialize the datatable
var datatable = $elm.DataTable();
// fix table border
$($elm.find('thead > tr')[0]).append('<span class="th-border"> </span>');
// swap the row up
$('span.swap .up').click(function() {
var previous = this.parentElement.parentElement.previousSibling,
parent = this.parentElement.parentElement;
if (previous && previous.nodeName && previous.nodeName === 'TR') {
var rowIndex1 = parseInt(datatable.row(previous).index()),
rowIndex2 = parseInt(datatable.row(parent).index()),
rowData1 = datatable.row(previous).data(),
rowData2 = datatable.row(parent).data();
rowData1.counter++;
rowData2.counter++;
datatable.row(rowIndex1).data(rowData2).draw;
datatable.row(rowIndex2).data(rowData1).draw;
}
});
// swap the row down
$('span.swap .down').click(function() {
var next = this.parentElement.parentElement.nextSibling,
parent = this.parentElement.parentElement;
if (next && next.nodeName && next.nodeName === 'TR') {
var rowIndex1 = parseInt(datatable.row(parent).index()),
rowIndex2 = parseInt(datatable.row(next).index()),
rowData1 = datatable.row(parent).data(),
rowData2 = datatable.row(next).data();
rowData1.counter++;
rowData2.counter++;
datatable.row(rowIndex1).data(rowData2).draw;
datatable.row(rowIndex2).data(rowData1).draw;
}
});
});
CSS:
.th-border {
display: table-cell;
border-bottom: 1px solid #111;
}
.swap {
display: table-cell;
vertical-align: middle;
pointer-events: all;
}
.swap i.up:before {
content: '\25b2';
}
.swap i.down:before {
content: '\25bc';
}