javascript - 无法更改 DataTable jQuery 中选定行的背景颜色

标签 javascript jquery datatables

我正在尝试突出显示或更改 jQuery 数据表中所选行的背景颜色。我正在使用 rowCallback 但没有任何效果。这是我的代码:

//..global variable , this is id of selected row
let selectedRowProfileId = ''; 

//..ready function
$(document).ready(function () {
if ($('#data-table').length !== 0) 
{
    $('#data-table').DataTable({
        autoFill: true,
        "scrollX": true,
        "columnDefs":
            [
                {
                    "targets": [1],
                    "visible": false,
                    "searchable": false
                },
            ],

    });
}});

//..Click event fired whenever a user click on a cell or row
$('#data-table tbody').on('click', 'td', function () {



const tr = $(this).closest('tr');

const table = $('#data-table').DataTable();
const data = table.row(tr).data();

selectedRowProfileId = data[1];

//..Update UI
UpdateUIBySelectedProfileId(selectedRowProfileId);
});

UpdateUIBySelectedProfileId(selectedRowProfileId){

  //..Here i do ajax call based on the selectedRowProfileId
  //..Upon receiving the respone in success bloc of ajax call
  //..i re-draw the table like this :
  const clients = JSON.parse(reponse);
  const table = $('#data-table').DataTable();
  table.clear().draw(); 

  clients.forEach(client => {
     table.row.add([
        client['LastKnownZone'],
        client['ProfileId'],
        client['macAddress'],
        client['ssId'],
        client['Statut'],,
        client['LastLocatedTimeString'],
     ]);
  });

  if (selectedRowProfileId !== '')
                {
                    table.rows().eq(0).each(function (index)
                    {

                        const row = table.row(index);
                        const data = row.data();
                        //console.log(data[1]);
                        if (data[1] === selectedRowProfileId)
                        {
                            $(row).css("background-color", "Orange");
                            //$(row).addClass('label-warning');
                            //console.log(row);
                        }

                    });
                }


                table.draw();

}

所以我想要实现的是在重绘表格时突出显示先前选择的行。

我想弄清楚上面的代码有什么问题。 任何帮助将不胜感激。

谢谢

最佳答案

您尝试从 rowCallback 中更改行背景颜色这不应该起作用,因为它是在呈现表格之前触发的。

相反,您可以将“着色”代码放在行点击处理程序中(按照建议 here )

下面的演示是为了说明这个概念:

const dataSrc = [
  {item: 'apple', cat: 'fruit'},
  {item: 'pear', cat: 'fruit'},
  {item: 'carrot', cat: 'vegie'}
];

const dataTable = $('#mytable').DataTable({
  dom: 't',
  data: dataSrc,
  columns: ['item', 'cat'].map(item => ({title: item, data: item}))
});

$('#mytable').on('click', 'tr', function(){
  $(this).toggleClass('selected');
  console.log(dataTable.row($(this)).data());
});
.selected {
  background: gray !important;
}

tbody tr:not(.selected):hover {
  cursor: pointer !important;
  background: lightgray !important;
}
<!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>

以上代码假定您使用'select' DataTable 的扩展

如果以上选择需要持久化(在重新绘制表格时,例如由 AJAX 调用触发),可以引入一个数组来存储表格记录的 ID(例如 const selectedRowIds = [] 在全局范围内)和 createdRow如果在 selectedRowIds 中找到行 ID,则可以使用选项在重新绘制时重新应用类 selected:

const dataTable = $("#mytable").DataTable({
    ...
    createdRow: (row, data, dataIndex, cells) => {
        if (selectedRowIds.indexOf(data.id) > -1)
            $(row).addClass("selected");
    }
});

此外,行点击处理程序应使用将所选行 ID 添加到/从 selectedRowIds 中添加/删除的逻辑进行扩展:

$("#mytable").on("click", "td", function () {
    //get clicked table row node
    const clickedRow = dataTable.row($(this).closest("tr"));
    //append/remove selected row 'id' property value to global array
    selectedRowIds = $(clickedRow.node()).hasClass("selected")
         ? selectedRowIds.filter(rowId => rowId != clickedRow.data().id)
         : [...selectedRowIds, clickedRow.data().id];
    //toggle class 'selected' upon clicking the row
    $(clickedRow.node()).toggleClass("selected");
});

您可以在 here 上找到完整的演示或使用浏览器的开发工具检查它,使用 this链接。

关于javascript - 无法更改 DataTable jQuery 中选定行的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55954549/

相关文章:

javascript - 无法在 Safari 上的 IndexedDB 中存储 Blob 类型

jquery - Firefox 中的等高 div 错误(?)

javascript - 将类应用于具有属性的元素

jquery - 如何在打印时将最后一页的页脚添加到数据表中

php - 如何从DataTables行中获取值?

javascript - 如何重新加载/刷新 jQuery 数据表?

javascript - 将 getElementById 返回值视为数组

javascript - Gulp 观看多个文件夹

javascript - 当还剩下一个远程结果时,Typeahead Remote 返回两个未定义

javascript - 有没有一种方法可以使用 Javascript 或 jQuery 隐藏列表中与元素和相邻列的高度相关的元素?