jQuery 根据内容更改jquery数据表的单元格背景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9078426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:17:58  来源:igfitidea点击:

change cell background of jquery datatable based on content

jqueryjquery-pluginsdatatables

提问by Gabor Forgacs

I am new to datatables - http://datatables.net/- . I am in trouble to find an example how I could change the background color of a cell based on its position and content.

我是数据表的新手 - http://datatables.net/- 。我很难找到一个示例,如何根据单元格的位置和内容更改单元格的背景颜色。

Something like this worked for me except that the highlighting of the selected row is now 'overcolored' in the cells which have changed background color. If I could get the class name of the row in the fnRowCallback then I could handle it.

像这样的东西对我有用,除了所选行的突出显示现在在已经改变背景颜色的单元格中“过度着色”。如果我可以在 fnRowCallback 中获得行的类名,那么我就可以处理它。

$(document).ready(function() {

   // Add a click handler to the rows - this could be used as a callback 
   $("#example tbody").click(function(event) {

      $(oTable.fnSettings().aoData).each(function() {
         $(this.nTr).removeClass('row_selected');
      });
      (event.target.parentNode).addClass('row_selected');
   });


   oTable = $('#example').dataTable({

      "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {

         $(nRow).children().each(function(index, td) {

            if (index == 6) {

               if ($(td).html() === "pending") {
                  $(td).css("background-color", "#078DC6");
               } else if ($(td).html() === "rendering") {
                  $(td).css("background-color", "#FFDE00");
               } else if ($(td).html() === "success") {
                  $(td).css("background-color", "#06B33A");
               } else if ($(td).html() === "failure") {
                  $(td).css("background-color", "#FF3229");
               } else {
                  $(td).css("background-color", "#FF3229");
               }
            }
         });
         return nRow;
      },
      "bProcessing": true,
      "bServerSide": true,
      "sAjaxSource": "scripts/server_processing.php",
      "sPaginationType": "full_numbers",
   });
});

采纳答案by Tom Maeckelberghe

$('table:last tr:nth-child(2) td:nth-child(2)').
  css("background-color", "#cccccc");

回答by mbeasley

I know the question was already answered, but I thought I would share how I was able to apply "conditional formatting" of sorts to various cells, in the following way:

我知道这个问题已经得到回答,但我想我会分享我如何能够通过以下方式将各种“条件格式”应用于各种单元格:

First, I added a class to each column during my datatables initialization:

首先,我在数据表初始化期间向每一列添加了一个类:

"aoColumns": [{
                "mDataProp": "serial",
                "sClass": "serial"
            }, {
                "mDataProp": "us",
                "sClass": "us"
            }...],

Then, I created an addFormat() function that was called each redraw (I had to do it this way because I have a live table that updates in realtime):

然后,我创建了一个 addFormat() 函数,每次重绘都会调用该函数(我必须这样做,因为我有一个实时更新的活动表):

"fnDrawCallback": function(oSettings) { addFormat(); },

In the addFormat function, I essentially defined all of my formatting rules, via CSS classes. I used a jQuery :contains extensionin order to apply very specific rules with regular expressions and such. My selectors for these rules would be tdand whatever class I had assigned to a column during datatables initialization:

在 addFormat 函数中,我基本上通过 CSS 类定义了所有格式规则。我使用了jQuery :contains 扩展名,以便使用正则表达式等应用非常具体的规则。我的这些规则的选择器将是td我在数据表初始化期间分配给列的任何类:

 $("td.us:containsRegex(/^[xtfv]$/)").addClass("s4 queue");

That worked very well for me.

这对我来说非常有效。

回答by AntonyManoj

You can change background color of cell dynamically respective of cell value by

您可以根据单元格值动态更改单元格的背景颜色

{"mData": "index", "sClass": "center" ,"fnRender": function(obj) {
                                              var index  = obj.aData.index;
                                              var isActive  = obj.aData.isActivated;
                                              if(isActive == true){
                                                  obj.oSettings.aoColumns[obj.iDataColumn].sClass = "greenBackground"
                                              }else{
                                                  obj.oSettings.aoColumns[obj.iDataColumn].sClass = "yellowBackground"
                                              }
                                              return index;
                                          } },

回答by Caner

I haven't tested this but something like this should give you an idea:

我还没有测试过这个,但这样的事情应该给你一个想法:

// Change i-th row j-th column
var rows = document.getElementById("myTable").getElementsByTagName('tr');
var columns = rows[i].getElementsByTagName('td');
jQuery( columns[j] ).css("background-color", "#cccccc");

回答by devlin carnate

Here's how to conditionally style the cells via createdCell, using DataTables 1.10+ syntax.

以下是如何createdCell使用DataTables 1.10+ 语法通过 有条件地设置单元格样式。

"columnDefs": [
{
        "targets": [6],
        "createdCell": function(td, cellData, rowData, row, col) {
            var color;
            switch(cellData) {
            case "pending":
                color = '#078DC6';
                break;
            case "success":
                color = '#FFDE00';
                break;
            case "failure":
                color = '#06B33A';
                break;
            default:
                color = '#FF3229';
                break;
            }
            $(td).css('background',color);
        }
    }
],

回答by Odysseus Ithaca

This worked for me. data[3] means column 4 of the row we're looking at (remember, arrays in javascript are zero-based, that is they start numbering at zero). But when we want to change the cell background, we use the .eq(3) syntax.

这对我有用。data[3] 表示我们正在查看的行的第 4 列(请记住,javascript 中的数组是从零开始的,即它们从零开始编号)。但是当我们想要改变单元格背景时,我们使用 .eq(3) 语法。

"createdRow": function ( row, data, index ) {
    if ( data[3] == "pending" ) {
        $('td', row).eq(3).css('background-color', '#078DC6');
    }
    if ( data[3] == "rendering") {
        $('td', row).eq(3).css('background-color', '#FFDE00');
    }

}