【问题标题】:Input type checkbox in php not same in htmlphp中的输入类型复选框与html中的不同
【发布时间】:2020-06-24 14:10:30
【问题描述】:

如果我想禁用带有 html 的复选框,我需要将其插入到输入标签中。

<input type="checkbox" class="someone" name="any"  disabled> html

但如果我想用 PHP 构建它并禁用取决于我将写的条件:

$question = 'foo';
        echo '<input type="checkbox" class="someone" name="any"';
                if ($question == 'foo'){
                    echo 'disabled';
                }
                echo '">php';
                echo '<br>';
                echo '<input type="checkbox" class="someone" name="any"  disabled> html';

如果您尝试,您会看到以相同方式编写但只有 html 有效的表单 google devtools

为什么????

【问题讨论】:

  • 两段代码不一样-看disabled后面多出来的"

标签: php html input checkbox echo


【解决方案1】:

上面 PHP 的问题是你错误地有一个额外的结束引号 -​​ 如果你使用 printf 你不需要像这样复杂/令人困惑的语法。

考虑:

printf(
    '<input type="checkbox" class="someone" name="any" value="1" %s />', 
    ( $question=='foo' ? 'disabled' : '' )
);

%s 是一个占位符,由三元运算符的值替换。

【讨论】:

    【解决方案2】:

    这可能是因为两个输入具有相同的名称属性。每个复选框都是一个唯一的输入元素,通常每个复选框都有自己独特的 name 属性值。我不完全确定,但是有两个同名的输入可能会导致浏览器出现不可预知的行为。

    提醒一下,您还可以通过使用内联字符串变量来简化编写代码的方式,如下所示:

    $question = 'foo';
    $disabled = $question ? 'disabled' : ''
    echo '<input type="checkbox" class="someone" name="any" '.$disabled.'>';
    

    更好的是,最好将 HTML 与 PHP 分开,例如:

    <?php
        $question = 'foo';
        $disabled = $question ? 'disabled' : '';
    ?>
    
    <input type="checkbox" class="someone" name="any" <?php echo $disabled; ?>>
    

    【讨论】:

      猜你喜欢
      • 2013-09-05
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多