• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

用户头像
it1352
帮助1

问题说明

我正在尝试基于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.

正确答案

#1

在此条件之前,您缺少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" ?>'>

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfhikj
系列文章
更多 icon
同类精品
更多 icon
继续加载