jquery datatable 多行(单行)选择(select),行获取/行删除
代码展示
// 示例数据源
var dataSet = [
['Tasman','Internet Explorer 5.2','Mac OS 8-X','1','C'],
['Misc','NetFront 3.1','Embedded devices','-','C'],
['Misc','NetFront 3.4','Embedded devices','-','A'],
['Misc','Dillo 0.8','Embedded devices','-','X'],
['Misc','Links','Text only','-','X'],
['Misc','Lynx','Text only','-','X'],
['Misc','IE Mobile','Windows Mobile 6','-','C'],
['Misc','PSP browser','PSP','-','C'],
['Other browsers','All others','-','-','U'],
//...
];
$(document).ready(function() {
$('#example').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
//这里插入数据使用的是`dataTable`(注意`dataTable`大小写)
$('#demo').dataTable( {
"data": dataSet,
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
{ "title": "Version", "class": "center" },
{ "title": "Grade", "class": "center" }
]
} );
} );
正常效果展示:
单选代码:
//1.首先获取datatable对象(注意大小写`DataTable()`):
var Dtable = $('#demo').DataTable();
$('#demo tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected') ) {
$(this).removeClass('selected');
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
}
单选后效果展示:
多选代码:
var Dtable = $('#demo').DataTable();
$('#demo tbody').on('click', 'tr', function () {
$(this).toggleClass('selected');
}
多选后效果展示:
获取选中行 :
var Dtable = $('#demo').DataTable();
$('button').click(function () {
alert( Dtable.rows('.selected').data().length +' row(s) selected' );
});
删除选中行 :
var Dtable = $('#demo').DataTable();
$('button').click(function () {
//单行删除
//Dtable.row('.selected').remove().draw(false);
//多行删除
Dtable.rows('.selected').remove().draw(false);
});
注意事项:
在获取datatable
的对象时,datatable
的大小写字母要区分开,不然会报错:
Uncaught TypeError: Dtable.row is not a function