简体   繁体   English

使用三元运算符php放置内联样式

[英]putting inline style using ternary operator php

I am trying to add css inline style based on a php variable's value. 我试图基于php变量的值添加css内联样式。 I tried doing so with ternary operator, and also I converted the variable value to float. 我尝试使用三元运算符执行此操作,并且还将变量值转换为float。 But the css is not being applied as expected. 但是没有按预期方式应用CSS。

       <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. 但是简单的内联样式效果很好。

You're missing the echo command prior to the condition. 您在条件之前缺少echo命令。 Basically if the condition returns true or false, the statements are being returned and not necessary being echoed. 基本上,如果条件返回true或false,则返回语句,而不必回显。

<?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" ?>'>

Not

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

but

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM