简体   繁体   English

在 html 中使用“php if”更改颜色背景

[英]Change a <td> color background with “php if” in html

I'm finishing a homework, but there is something bothering me, which is the fact that I cant change a <td></td> background color using php.我正在完成作业,但有件事困扰着我,那就是我无法使用 php 更改<td></td>背景颜色。

This is a code from html using some classes of php and all that stuff这是来自 html 的代码,使用 php 的某些类和所有这些东西

<?php
<td 
<?php
if ($produtos->dtfora==1001-01-01) {
    echo "style="; background-color;darkred;"";
}
?>
>
<?php echo $produtos->dtfora; ?>
</td>

There are no error messages, it just doesn't work or change anything没有错误消息,它只是不起作用或改变任何东西

you must do it like this:你必须这样做:

<?php $style = 'background-color:darkred'; ?>

<td style="<?php echo $style ?>">
    // Your Content
</td>

There are couple small issues with this.这有几个小问题。
First, there are two opening php tags.首先,有两个开放的php标签。 Fixing this would turn the code into the following:修复此问题会将代码变为以下内容:

<td 
<?php
    if ($produtos->dtfora=="1001-01-01") {
        echo 'style="; background-color;darkred;"';
    }
?>
>
<?php echo $produtos->dtfora; ?>
</td>

This is still not easy to read or easy to maintain, so moving the result of the statement into a seperate variable would be ideal:这仍然不容易阅读或维护,因此将语句的结果移动到单独的变量中是理想的:

<?php
    // Define default style
    $style = "";
    // If the statement is matched, set the style variable to the custom color
    if ($produtos->dtfora=="1001-01-01") {
        $style = "background-color: darkred;";
    }
?>

<!-- Use the style variable, either empty or filled with color into the style attribute of the td -->
<td style="<?php echo $style; ?>">
    <?php echo $produtos->dtfora; ?>
</td>
<?php

$changeBg = "background-color:red";

?>

<td style="<?php echo $changeBg ?>">
   Email ID
<td>

It should be like below.它应该如下所示。

<?php
if ($produtos->dtfora=="1001-01-01") {
    echo "style='background-color:darkred";
}

for this you can simple using a class for this and add this class according to your condition.为此,您可以简单地使用 class 并根据您的条件添加此 class。 example:例子:

<style>
.productos_td: {background-color:darkred;}
</style>
<?php
if ($produtos->dtfora==1001-01-01) { ?>
<td class="productos_td">
<?php } else{ ?> <td> <?php } ?>
</td>

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

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