更改同一表格单元格中文本和图标的颜色

时间:2017-05-14 08:28:39

标签: javascript php

我知道如何为每个文本值设置不同的颜色。

首先,我检查并将$ driverStatus设置为字符串:

if ($log->field_is_online_value == 'online') {
    $driverStatus = 'Online';
} elseif ($log->field_is_online_value == 'offline') {
    $driverStatus = 'Offline';
} else {
    $driverStatus = 'Busy';
}

然后形成表并从PHP粘贴字符串:

<table id="locations">
    <tr><th>Driver status</th></tr>
    <tr><td>'.$driverStatus.'</td></tr>
</table>

最后分别检查文字和改变颜色:

var cells = document.getElementById("locations").getElementsByTagName("td");

for (var i = 0; i < cells.length; i++) {
    if (cells[i].innerHTML == "Online") {
        cells[i].style.color = "#5CB85C";
    } else if (cells[i].innerHTML == "Offline") {
        cells[i].style.color = "#D9534F";
    } else if (cells[i].innerHTML == "Busy") {
        cells[i].style.color = "#F0AD4E";
    }
}

如果字符串如下所示,我需要为文本和图标设置相同的颜色:

$driverStatus = 'Online&nbsp&nbsp<i class="glyphicon glyphicon-ok"></i>';
$driverStatus = 'Offline&nbsp&nbsp<i class="glyphicon glyphicon-off"></i>';
$driverStatus = 'Busy&nbsp&nbsp<i class="glyphicon glyphicon-time"></i>';

1 个答案:

答案 0 :(得分:0)

$driverStatus = 'Online&nbsp&nbsp<i class="glyphicon glyphicon-ok"></i>';
//...

var cells = document.getElementById("locations").getElementsByTagName("td");

for (var i = 0; i < cells.length; i++) {
    var cell = cells[i];
    var icon = cell.getElementsByTagName("i")[0];

    if (cell.innerHTML == 'Online&nbsp&nbsp<i class="glyphicon glyphicon-ok"></i>') {
        cell.style.color = "#5CB85C";
        icon.style.color = "#5CB85C";
    } else if (...) {
        ...
    }
}