如何根据值更改HTML表(动态创建)单元格的颜色?

我有以下功能可以动态生成表格。根据单元格的某个值,我想将单元格涂成红色。

function makeTable(container, data) {
            var table = $("<table/>").addClass('table table-striped');

            $.each(data, function(rowIndex, r) {
                var row = $("<tr/>");

                $.each(r, function(colIndex, c) {

                    row.append($("<t"+(rowIndex == 0 ?  "h" : "d")+"/>").text(c));

                    if( $.trim(c.toLowerCase() ) === "validated" ){
                        console.log("Paint it red"); 

<!-- this condition works and I do see "Paint it red" in the console. I tried multiple things at this stage, without success, to color the cell or the entire row red. I do have an inline stylesheet declared in the HTML, but I do not know what should I use it on. 

                    }else {
                        console.log("Leave it alone");

                    }                   
                });
                table.append(row);

            });

            return container.html(table);

        }

谢谢, 缺口

评论
Viola
Viola

您可以在jquery元素上调用addClass():

function makeTable(container, data) {
   var table = $("<table/>").addClass('table table-striped');

   $.each(data, function(rowIndex, r) {
      var row = $("<tr/>");

      $.each(r, function(colIndex, c) {
         var cellMarkup = "<t"+ (rowIndex == 0 ?  "h" : "d") +"/>";
         var cell = $(cellMarkup); // now you have a jQuery element to call addClass on!
         cell.text(c); // sorry I forgot to put back your cell text

         if( $.trim(c.toLowerCase() ) === "validated" ){
            cell.addClass("error");

         } else {
            cell.addClass("selected");

         }
         row.append(cell);

       });
       table.append(row);

    });

    return container.html(table);
}
点赞
评论