doufan9377 2017-06-09 23:42
浏览 39
已采纳

PHP中的Javascript条件格式

I'm trying to do a conditional formatting for the $row->cap24hrChange results. If it's < 0, I want the value to be colored red, otherwise it should be green. I'm not getting any response from the script.

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

EDIT

On a very related note: how could I work around that code so as to include icons on the right (↑ and ↓) for values >0 and <0, respectively?

EDIT(2)

I figured it out with the help of $foo = "bar".$foo

<td style="color:<?php if($row->cap24hrChange > 0){ echo "green"; $row->cap24hrChange = $row->cap24hrChange . " 
  • 写回答

1条回答 默认 最新

  • doujiang9887 2017-06-10 00:13
    关注

    Don't use javascript to do that. It's something you can know at the before page load so you can put it in static.

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

    But be careful you don't have the case $row->cap24hrChange == 0 in your code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?