【问题标题】:Use echo in a css class [closed]在 CSS 类中使用 echo [关闭]
【发布时间】:2013-11-19 13:13:40
【问题描述】:

我在项目的不同页面中使用 php echo 来更新每天都在变化的百分比值。这个值可以是负数也可以是正数。

这是我的代码:

<i class="icon-thumbs-up"><strong> <?php $file = file('include.txt');echo $file[n]; ?></strong></i>

我正在使用带有 Bootstrap 模板的 FontAwesome 图标。像这样一切正常。

现在,如果百分比是负数,我想使用 class="icon-thumbs-down" 而不是 class="icon-thumbs-up"。

我已经尝试过使用

<i class="<?php $file = file('include.txt');echo $file[n]; ?>"><strong> <?php $file = file('include.txt');echo $file[13]; ?></strong></i>

为了在所有页面上更改它。

但是,这不起作用。感谢您的任何提示!

澄清一下:

<i class="icon-thumbs-up"><strong> <?php $file = file('include.txt');echo $file[0]; ?></strong></i>

include.text 的内容:第 1 行的 0.58% -> 一切正常。我竖起大拇指,旁边的值为 0.58%。

现在我尝试更改为:

<i class="<?php $file = file('include.txt');echo $file[1]; ?>"><strong> <?php $file = file('include.txt');echo $file[0]; ?></strong></i>

include.text 的内容:第 1 行为 0.58%,第 2 行为 icon-thumbs-up。(我想每天在 include.txt 中将其更改为 icon-thumbs-up 或 icon-thumbs -down,取决于第 1 行的值。)

【问题讨论】:

  • 不清楚你想听什么。你的代码试图做什么?换句话说,预期的输出是什么?另外,include.txt 是什么?

标签: php html css


【解决方案1】:

如果来自file('include.txt') 的值是整数,那么您可以使用三元运算符来回显正确的css 类,例如。像这样:

<li class="<?php echo (int) $file[0] < 0 ? 'icon-thumbs-down' : 'icon-thumbs-up'; ?>"></li>

【讨论】:

  • 不工作。我用-1和1试过了,拇指总是向上的。另一个问题是这些值就像 -0.75 或 1.66 - 总是有两位小数。
  • @MichaelHazelwood 所以它们是浮点数而不是整数,使用(float)。还要检查$file[0] 的值以确保一切正常。
  • 使用 % 百分比值为-0.63,在第二部分正确显示。然而,无论我输入什么值,拇指仍然一直向上。
  • 发现了问题:) 没有引用 include.txt。现在我将代码更改为 class="" 一切正常。非常感谢!
【解决方案2】:

这有点难以回复,因为您的代码不是很清楚。但是,我可以通过一个示例向您提供以下建议:

$someInt = 10;
echo $someInt < 0 ? 'icon-negative' : 'icon-positive'; // will echo positive

$someInt = -3;
echo $someInt < 0 ? 'icon-negative' : 'icon-positive'; // will echo negative

这是一个简短的 if/else(三元)。为了演示它是如何工作的,这在完整的语法中是相同的:

$someInt = -3;
if($someInt < 0){
    echo 'icon-negative';
}
else{
    echo  'icon-positive'; 
}

【讨论】:

    【解决方案3】:

    我会做以下事情:

    <?php
    // your logic here, move in another file if this gets bigger:
    function percentage($nb) {
      $file = file('include.txt');
      return $file[$nb];
    }
    ?>
    <i class="<?php echo percentage(5) > 0 ? 'positive' : 'negative' ?>">
      <strong>Text</strong>
    </i>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      相关资源
      最近更新 更多