簡體   English   中英

無法更改DataTable jQuery中所選行的背景顏色

[英]Unable to change background color of selected row in DataTable jQuery

我試圖突出或更改jQuery Datatable中所選行的背景顏色。 我正在使用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更改行背景顏色,這不應該起作用,因為它是在呈現表之前觸發的。

相反,您可以將“着色”代碼放在行單擊處理程序中(如此處所示

以下演示是為了說明這個概念:

 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的“select”擴展名

如果上面的選擇需要是持久的(在表重新繪制時,例如由AJAX調用觸發),可以引入一個存儲表記錄的id的數組(例如,全局范圍內的const selectedRowIds = [] )和createdRow選項可以為了重新應用類可以采用selected在再拉如果行ID內發現selectedRowIds

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

此外,應使用邏輯擴展行單擊處理程序,該邏輯將向/從selectedRowIds追加/刪除所選行id:

$("#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");
});

您可以在此處找到完整的演示 ,或使用鏈接通過瀏覽器的Dev Tools進行檢查。

嘗試更改行的td標記的背景顏色。

$('td', row).css('background-color', 'orange');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM