0

如果我想禁用带有 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

在此处输入图像描述

为什么????

4

2 回答 2

2

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

考虑:

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

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

于 2020-03-12T13:59:55.237 回答
0

这可能是因为两个输入具有相同的名称属性。每个复选框都是一个唯一的输入元素,并且通常每个复选框都有自己独特的 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; ?>>
于 2020-03-12T14:04:19.520 回答