【问题标题】:Is there any better way to change the style of an element with PHP?有没有更好的方法来用 PHP 改变元素的样式?
【发布时间】:2021-09-26 08:53:53
【问题描述】:

有没有更好的方法来实现相同的结果,通过在外部使用 PHP 而不是在实际的 HTML 标记内部?这种方法效果很好,但是像这样将 PHP 标记放在 HTML 标记中似乎有点不方便。特别是当您在单击提交时必须调整多个属性时。或者更糟糕的是,同一个表单中多个元素的多个属性!

作为一个绝对的 PHP 初学者,我不知道...

<form method="post" action="">
  <input type="text" name="input" value="
    if (isset ($_POST['submit']) ) {
      $input = $_POST['input'];
      echo $input;
    }
  " />
  <input type="submit" name="submit" />
</form>

请注意: 上面的脚本可能有问题,因为我直接写在这个论坛帖子里,没有外部测试。我只是想指出它的想法:仅使用 PHP 调整样式、值或任何其他属性。

【问题讨论】:

  • 您可以使用三元运算符来缩短它。是的,或者您可以在其他地方进行大部分处理,并在 PHP 中回显变量。为了更高级,您也许还应该研究各种可用的模板引擎。

标签: php styles echo element


【解决方案1】:

如果您不想将 PHP 逻辑放入 HTML 代码中,您可以在 HTML 代码上方编写 php 逻辑并将结果存储在一个变量中,然后您可以将其放入 HTML 代码中。

例如:

<?php 
$input = '';
if (isset ($_POST['submit']) ) {
  $input = $_POST['input'];
} 
?>
<form method="post" action="">
 <input type="text" name="input" value="<?php echo $input; ?>" />
 <input type="submit" name="submit" />
</form>

【讨论】:

    【解决方案2】:

    如果你需要让你的代码更短,你可以使用短标签

    <form method="post" action="">
      <input type="text" name="input" value="<?= isset ($_POST['submit']) ? $_POST['submit'] : '' ?>" />
      <input type="submit" name="submit" />
    </form>
    
    

    你可以在渲染前提供你需要的一切

    <?php
        $html = [
             'forms' => [
                  'myForm' => [
                        'action' => '',
                       'method' => 'POST',
                       'myInput' => [
                            'value' => isset ($_POST['submit']) ? $_POST['submit'] : ''
                        ],
                  ],
             ],
        ];
    ?>
    <form method="<? $html['forms']['myForm']['method'] =?>" action="<?= $html['forms']['myForm']['method'] ?>">
      <input type="text" name="input" value="<?= $html['forms']['myForm']['myInput']['value'] ?>" />
      <input type="submit" name="submit" />
    </form>
    
    

    还有一些工具可以让您在 html 中使用 php 更具可读性。 Using PHP as a template engine

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2019-12-19
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多