我使用Ternary Operator方法选择选择框的代码:
Ternary operator let us return one of two values based on a given condition. It’s syntax is like below.
(expression)?(if expression is true):(if expression is false)
mycode的:
<select class="form-control contentgroup input-sm" name="access">
<option value="1" <?php echo ($access = 1) ? 'selected' : ''; ?>>1</option>
<option value="2" <?php echo ($access = 2) ? 'selected' : ''; ?>>2</option>
<option value="3" <?php echo ($access = 3) ? 'selected' : ''; ?>>3</option>
</select>
但我输出我看到所有选项都被选中:
<select class="form-control contentgroup input-sm" name="access">
<option value="1" selected>1</option>
<option value="2" selected>2</option>
<option value="3" selected>3</option>
</select>
如何解决这个问题?
答案 0 :(得分:5)
这是一个错字。您正在使用赋值运算符=
而不是比较运算符==
或===
<option value="1" <?php echo ($access == 1) ? 'selected' : ''; ?>>1</option>
<option value="2" <?php echo ($access == 2) ? 'selected' : ''; ?>>2</option>
<option value="3" <?php echo ($access == 3) ? 'selected' : ''; ?>>3</option>
答案 1 :(得分:0)
使用等价运算符代替赋值运算符:
<option value="1" <?php echo ($access == 1) ? 'selected' : ''; ?>>1</option>
<option value="2" <?php echo ($access == 2) ? 'selected' : ''; ?>>2</option>
<option value="3" <?php echo ($access == 3) ? 'selected' : ''; ?>>3</option>
您可以使用==
或===
,而后者则用于严格比较。