首页 > 解决方案 > 更改数据表中单击的行的颜色

问题描述

如何更改数据表单击行的颜色?

我有我的数据表和一个 JavaScript 来对点击的行的数据进行一些操作:

var table = $('#myTable').DataTable();
$('#myTable tbody').on('click', 'tr', function () {
   var data = table.row( this ).data();
   // below some operations with the data
   // How can I set the row color as red?
} );

谢谢

标签: javascriptjquerydatatable

解决方案


在这种情况下,我不确定 DataTable 的相关性,但您可以使用 jQuery 来做到这一点。

示例:https ://codepen.io/alexpetergill/pen/ccd10f785e6b6d9e2c2b2503b219eab4

var table = $('#myTable').DataTable();
$('#myTable').on('click', 'tr', function () {
   var data = table.row( this ).data();
   // below some operations with the data
   // How can I set the row color as red?
  $(this).addClass('highlight').siblings().removeClass('highlight');
});

如果您想在分页后删除突出显示,那么我建议您使用 DataTables 自定义事件之一...

$('#myTable').on('draw.dt', function () {
  $(this).find('.highlight').removeClass('highlight');
});

https://datatables.net/reference/event/draw


推荐阅读