繁体   English   中英

如何添加条件并更改表格行的颜色

[英]How to add condition and change the color of table row

我有一个JavaScript,它将从JSON读取值并在HTML页面中动态创建一个表。

<div style="width:700px;padding:20px;S">
            <h1 style="text-align:center"><i style="color:#ccc">ALM Server Availability</i></h1>

            <table id="records_table" class="table">
                <tr>
                    <th>Server Name</th>
                    <th>Availability %</th>
                </tr>
            </table>
        </div>

JQUERY:

function availshow(series) {
    // 1. remove all existing rows
    $("tr:has(td)").remove();

    $.each(series.data.hostgroup.hosts, function (index, test) {
       $('<tr>').append(
            $('<td>').text(test.name),
            $('<td>').text(parseInt((test.time_up/86400)*100)),
        ).appendTo('#records_table');           
    });
 }

现在我需要检查条件是否(test.time_up/86400)*100) < 100 ,那么我需要将该特定行变成红色。 我该如何实现。

您可以这样做,遍历每个tr然后寻找第二个td

$('#records_table tr').each(function() {
  var $td = $(this).find('td:eq(1)');
  var value = $td.text();
  if (parseInt(value) < 100) {
    $td.css('background-color', 'red');
  }
});

您的JQuery功能应该是这样的:

    var i=0
    function availshow(series) {
            // 1. remove all existing rows
            $("tr:has(td)").remove();

            $.each(series.data.hostgroup.hosts, function (index, test) {
            i=(test.time_up/86400)*100);
               $("<tr"+(i < 100 ? "class:'redBlock'": "")+">").append(
                    $('<td>').text(test.name),
                    $('<td>').text(parseInt((test.time_up/86400)*100)),
                ).appendTo('#records_table');           
            });
         }

然后在.css文件中使用所需的所有样式创建该类:

.redBlock{
background-color:red;
}

希望我能帮上忙。 快乐编码:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM