使用三元运算符php放置内联样式 [英] putting inline style using ternary operator php

查看:74
本文介绍了使用三元运算符php放置内联样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试基于php变量的值添加CSS内联样式. 我尝试使用三元运算符执行此操作,并且还将变量值转换为float.但是css并未按预期应用.

I am trying to add css inline style based on a php variable's value. I tried doing so with ternary operator, and also I converted the variable value to float. But the css is not being applied as expected.

       <tbody>
        <?php
        $totalLeaveTaken = 0.00;
        $totalBalance = 0.00;
            foreach ($GetEmployeeLeaveBalance as $member):
                $totalLeaveTaken += $member['usedDays'];
                $totalBalance += $member['Remaining_Leave_Days'];
                $leaveBalance = floatval($member['Remaining_Leave_Days']);
            ?>
            <tr>
                <td><?php echo $member['title']; ?></td>
                <td><?php echo $member['maxDays']; ?></td>
                <td><?php echo $member['usedDays']; ?></td>
                <!-- <td><?php echo gettype($leaveBalance);?></td> -->
                <td
                <?php 
                ($leaveBalance < 0) ? 
                "style='background-color:red;'" : "style='background-color:green;'"
                ?>
                >
                <?php echo $member['Remaining_Leave_Days']; ?>    
                </td>
            </tr>
        <?php endforeach; ?>
        <tr>
            <td></td>
            <td></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo number_format($totalLeaveTaken, 2); ?></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo 
            number_format($totalBalance, 2); ?></td>
        </tr>
        </tbody>

但是简单的内联样式效果很好.

But the simple inline styling is working fine.

推荐答案

在此条件之前,您缺少echo命令. 基本上,如果条件返回true或false,则返回语句,而不必回显.

You're missing the echo command prior to the condition. Basically if the condition returns true or false, the statements are being returned and not necessary being echoed.

<?php
echo ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"
?>

边注,一种更好的做法:

Sidenote, A better practice:

由于两个返回的字符串都是样式,因此重复它是没有意义的(开发人员很懒::).所以你可以简单地写:

Since both of the returned strings are style, there's no point in repeating it (developers are lazy :] ). So you can simply write:

<td style='background-color: <?php echo ($leaveBalance < 0) ? "red" : "green" ?>'>

这篇关于使用三元运算符php放置内联样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆