css - 数据表在满足特定条件时设置行颜色

标签 css datatables

表格的每一行都有一个名为“id”的属性。

我想为“id”为 8 的行设置红色背景。

var selectedId = 8;

table.rows().every( function ( rowIdx, tableLoop, rowLoop ) {               
    if (this.data().id == selectedId) {
        $(table.row(rowIdx).node()).css('background-color', 'red'); // <-  does not work                  
        $(table.row(rowIdx).node()).addClass("redBackgroundClass"); // <-does not work
    }       
});

如何根据行的 id 值为其动态添加红色背景?

请注意

事实上,我已经将上面的代码简化为:

var node =$(table.row(0).node());
console.log(node); // <-- ok, console prints "<tr>"
node.css("background-color","red"); // <- does not work

最佳答案

可能最简单的方法是设置一个包含红色背景色的 css 类,然后在加载 dataTable 后,将该类分配给 ID 为 8 的行。您可以这样做这与 DataTables 初始化中的 rowCallback 选项有关:

$(document).ready(function() {
    $('#example').DataTable({
        //Other setup/config options go here
        rowCallback: function(row, data){
            if(data["id"] == 8){ //I'm assuming you're using object JSON/ajax, if not,
                                 //you'll have to find where in the data[] object the id is
                $(row).addClass("redBackgroundClass");
                //Or alternatively:
                //$(row).css("background-color","red"); if you don't want to make a css class
        }
    });
} );

使用此代码块,只要您有一个名为“redBackgroundClass”的 css 类和适当的背景属性,id 为 8 的所有行都将具有红色背景。

编辑:根据@Carl 的评论,您实际上不必有一个单独的 css 类,您可以根据需要设置该行的 css 背景色。我已将两者都包含在代码中。

编辑 2:如果您由于某种原因无法访问/修改 DataTables 初始化,这里有另一种方法:

var table = $('#example').DataTable(); //You don't have this line, but just note the name
                                       //'table' is the name of the DataTable object

var row = table
    .row('8') //This assumes that the official DT row index is named "8", if instead you
    .node();  //want the actual 8th row, just remove the ' marks and use row(8)

$(row).css("background-color","red");

编辑 3: 您已经正确地指出此代码与您的示例等效,但请注意,不同之处在于您的示例之前有一个 if 语句。我在 DataTables 文档中得到了那个例子,所以它的语法是正确的。我认为您的问题必须是 if 语句永远不会计算为真,或者您弄错了 data() id 的位置。尝试单步执行并查看您是否可以确认这些值是否符合您的预期。

关于css - 数据表在满足特定条件时设置行颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38316522/

相关文章:

css - 为什么 Font Awesome 在我的 Shadow DOM 中不起作用?

php - jQuery 数据表将日期显示为 [object Object]

javascript Datatable.js 如何根据上一列显示值

javascript - 为 DataTables.js 元素提供特定的 id/class/names

html - CSS 无法识别

javascript - 为 anchor 添加平滑滚动效果

jQuery Datatables 绘制在过滤方法后不起作用

mysql - 更正表中一对多、多对多的关系错误

php - 使用 php 将类添加到 li 然后在每第三个元素之后交替?

html - 当您单击其中一个框时,它会更改颜色并保持该颜色