Javascript PHP 内的条件格式

Javascript conditional formatting inside PHP

我正在尝试对 $row->cap24hrChange 结果进行条件格式化。如果它是 < 0,我希望该值是红色的,否则它应该是绿色的。我没有收到脚本的任何响应。

<table><head><style>
td {text-align: right;}
</style></head><table>
    <thead>
        <tr>
            <th>#Rank</th>
            <th>Name</th>
            <th>Price</th>
            <th>Mkt Cap</th>
            <th>Volume</th>
            <th>Supply</th>
            <th>24h(%)</th>
        </tr>
    </thead>
    <tbody>
        <?php function compare($a, $b) {
            return intval($a->position24) - intval($b->position24);
        } 

        $json = file_get_contents('http://www.coincap.io/front');
        $data = json_decode($json);
        usort($data, 'compare'); 
        ?>
        <?php foreach ($data as $row) { ?>
        <tr>
            <td><?= $row->position24; ?></td>
            <td><?= $row->long; ?></td>
            <td><?= number_format($row->price, 4); ?><\td>
            <td><?= number_format($row->mktcap, 2); ?><\td>
            <td><?= number_format($row->volume, 2); ?><\td>
            <td><?= number_format($row->supply, 2); ?><\td>
            <td><?= $row->cap24hrChange; echo "<script type=\"text/javascript\"> var trTags = document.getElementsByTagName("td"); for (var i = 0; i < trTags.length; i++) { var tdEightEl = trTags[i].children[7]; if (tdEightEl.innerText < 0) {tdEightEl.style.color = "red"; } else if (tdEightEl.innerText > 0) {tdEightEl.style.color = "green"; } }</script>";?></td>
        </tr>
        <?php } ?>
    </tbody>
</table>

编辑

一个非常相关的说明:我如何解决该代码以便在右侧(↑ 和 ↓)包含值 >0 和 <0 的图标?

编辑(2)

我在 $foo = "bar".$foo

的帮助下弄明白了
<td style="color:<?php if($row->cap24hrChange > 0){ echo "green"; $row->cap24hrChange = $row->cap24hrChange . "  ";}else if($row->cap24hrChange < 0){ echo "red"; $row->cap24hrChange = $row->cap24hrChange . "  ";}?>"><?= $row->cap24hrChange;?></td>

不要使用 javascript 来做到这一点。这是您可以在页面加载前知道的内容,因此您可以将其置于静态。

<td style="color:<?php if($row->cap24hrChange > 0){ echo "green"; }else if($row->cap24hrChange < 0){ echo "red"; }?>"><?= $row->cap24hrChange;?></td>

但请注意,您的代码中没有 $row->cap24hrChange == 0 的情况。