在我的数据表中,我要删除当用户单击该列的顺序图标时具有特定字段为空的行。
在此示例中,我要删除“ John”并在用户单击“城市”时对列进行排序:
Name Sirname Gender City
Nick S. M Rome
John R. M
Mary D. F London
此代码有效,但前提是我单击两次DataTable的订购图标。第一个匹配项将对列进行排序,第二个匹配项将删除行。
var table = $('#datatable').DataTable();
$('#datatable').on( 'order.dt', function () {
var order = table.order();
var data = table.rows().data();
if (order[0][0]== 3){
if(data[0][3] == ''){
table.row().remove().draw();
}
}
});
如何单击即可删除激发的行并对列进行排序?
答案 0 :(得分:1)
如果您需要带有空白字段city
的条目以在单击City
列标题时被永久删除,我建议采用以下解决方案:
const srcData = [
{name: 'Nick', surname: 'S.', gender: 'M', city: 'Rome'},
{name: 'John', surname: 'R.', gender: 'M', city: ''},
{name: 'Mary', surname: 'D.', gender: 'F', city: 'London'},
{name: 'George', surname: 'K.', gender: 'M', city: ''}
];
$('#mytable').DataTable({
dom: 't',
data: srcData,
columns: ['name', 'surname', 'gender', 'city'].map(header => ({title: header, data: header}))
});
$('thead th').unbind('click').on('click', function(e){
//grab the table and column being affected
const table = $(this).closest('table').DataTable();
const column = table.column($(this));
//define sort order to set (default 'asc')
const sortingOrder = $(this).hasClass('sorting_asc') ? 'desc' : 'asc';
//remove entries where 'city' is empty if 4-th column is clicked
if(column.index() == 3) {
//get an array of indexes of 'bad' rows
const badRows = [];
table.rows().every(function(rowIndex){
if(this.data().city == '') badRows.push(rowIndex);
});
//get those badRows removed
table.rows(badRows).remove();
}
//do default action - sort table
table.order([column.index(), sortingOrder]).draw();
}).on('mousedown', e => e.preventDefault());
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>