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

问题描述 投票:0回答:2

我有一个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的值,然后我需要将该特定行变成红色。我怎样才能实现它。

javascript jquery html
2个回答
2
投票

你可以这样做,循环每个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');
  }
});

1
投票

你的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;
}

希望我能提供帮助。快乐编码:)

© www.soinside.com 2019 - 2024. All rights reserved.