【问题标题】:Javascript conditional formatting inside PHPPHP中的Javascript条件格式
【发布时间】:2017-06-09 23:42:57
【问题描述】:

我正在尝试对$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 和

编辑(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 php html api conditional-formatting


    【解决方案1】:

    不要使用 javascript 来执行此操作。这是您在页面加载之前可以知道的内容,因此您可以将其设置为静态。

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

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

    【讨论】:

    • 这真是太棒了!谢谢=)
    猜你喜欢
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2020-02-09
    • 2018-03-01
    • 2020-11-06
    • 2013-07-03
    • 1970-01-01
    • 2014-09-09
    相关资源
    最近更新 更多