本文介绍了无法更改DataTable jQuery中选定行的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试突出显示或更改jQuery Datatable中所选行的背景颜色.我正在使用 rowCallback ,但没有任何反应.这是我的代码:

I am trying to highlight or change the background color of the selected row in jQuery Datatable. I am using rowCallback but nothing is working. Here is my code :

//..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();

}

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

So What i want to achieve is to highlight the previously selected row upon redrawing the table.

我正在尝试找出上述代码出了什么问题.任何帮助将不胜感激.

I am trying to figure out what is wrong with the above code.Any help would be appreciated.

谢谢

推荐答案

您尝试在 rowCallback 不起作用,因为它是在呈现表之前触发的.

You try to change row background color from within rowCallback which is not supposed to work, since it is triggered before table is rendered.

相反,您可以在行点击处理程序中放置着色"代码(如建议在此处)

Instead, you may put 'coloring' code inside row click handler (as suggested here)

以下演示是为了说明该概念:

Following demo is to illustrate that concept:

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>

以上代码假定您使用'选择' 不是 > DataTable扩展

Above code presumes that you're not using 'select' extension for DataTable

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

If above selection is required to be persistent (upon table re-draw, e.g. triggered by AJAX-call), there can be introduced an array that stores id's of table records (e.g. const selectedRowIds = [] within global scope), and createdRow option can be employed in order to re-apply class selected upon re-draw if row id is found within selectedRowIds:

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

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

Also, row click handler should be extended with the logic that will append/remove selected row id into/from 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");
});

您可以在此处找到完整的演示.或使用浏览器的开发工具,使用链接进行检查.

You may find the complete demo over here or inspect that with your browser's Dev Tools, using this link.

这篇关于无法更改DataTable jQuery中选定行的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:17