簡體   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