我如何根据值更改标签中文本的颜色

时间:2019-07-04 08:43:56

标签: javascript html css ajax

我使用ajax技术,我想将值发送到div标记,但要取决于表中的值。我认为这里需要一个循环,但是如何正确执行呢?

我使用xampp。后端php。

index.php

<li class="nav-item">
    <a href="#" class="btn btn-info" role="button" 
    onclick="taskphp()">Tapşırıqlar</a>
</li>

javascript.js

function taskphp() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("body").innerHTML = this.responseText;
            let state = document.getElementById("state");
            let stateValue = document.getElementById("state").innerHTML;
            switch(stateValue) {
                case "duzelib":
                state.style.color = "green";
                break;
                case "duzelme prosesinde":
                state.style.color = "yellow";
                break;
                case "duzelmeyib":
                state.style.color = "red";
                break;
                default:
                state.style.color = "white";
            }
        }
    };
    xhttp.open("GET", "IT/tasks.php", true);
    xhttp.send();
}

tasks.php

<?php while($row = $result->fetch_assoc()) {
    echo  "<tbody><tr>";
    echo "<td>".$row["task"]."</td>";
    echo "<td>".$row["description"]."</td>";
    echo "<td>".$row["task_objects"]."</td>";
    echo "<td id=\"state\">".$row["state"]."</td>";
    echo "<td>".$row["entrance_date"]."</td>";
    echo "<td>".$row["execute_date"]."</td>";
    echo "<td>".$row["source"]."</td>";
    echo "<td>".$row["month"]."</td>";
    echo "</tr></tbody>";
}
?>

我使用switch,我只能更改列表中第一个元素的颜色,我需要根据其值更改所有元素的颜色

1 个答案:

答案 0 :(得分:0)

只需记住几件事。

以这种方式进行设置,最终将得到一堆具有id为“ state”的元素。从理论上讲,id对于单个HTML元素应该是唯一的。这就是为什么我们有getElementById但没有getElementsbyId的原因。

您知道多个元素之间可以共享什么?上课!因此,您要做的第一件事就是更改您的php,这样

echo "<td id=\"state\">".$row["state"]."</td>";

成为

echo "<td class=\"state\">".$row["state"]."</td>";

因此,现在可以使用getElementsByClassName将所有类型为'state'的元素检索为数组。然后,您可以遍历该数组,然后分别在每个“状态”元素上运行switch语句:

const states = document.getElementsByClassName("state");
for (const state of states) {
    const stateValue = state.innerHTML;
    switch(stateValue) {
        case "duzelib":
            state.style.color = "green";
            break;
        case "duzelme prosesinde":
            state.style.color = "yellow";
            break;
        case "duzelmeyib":
            state.style.color = "red";
            break;
        default:
            state.style.color = "white";
      }
}
相关问题