php - 如何在 html 选项标签中使用 php 条件
问题描述
我有这个功能,当 $selected 等于 $row['id'] 时,我想在“option”标签中使用“selected”属性。请注意这不是 php 代码之间的常见 html 标签,请注意在 while 循环中每次都将 html 选项标签添加到 $output 变量中。
public function getCategoriesList(&$output = '',
$parent = 0, $seprator = '', $selected=1)
{
$sql = "SELECT * FROM categories WHERE `parent_id` = $parent ";
$stmt = $this->pdoConnection->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output .= "<option value=".$row['id']." ($row[id]==$selected)? selected :''>
".$seprator.$row['title']."
</option>";
$this->getCategoriesList($output, $row['id'],
$seprator . ' - ');
}
return $output;
}
解决方案
您可以为所选属性创建单独的条件。例子:
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$selected = $row['id'] == $selected ? "selected='selected'" : '';
$output .= "<option value='{$row['id']}' {$selected}>{$seprator}{$row['title']}</option>";
$this->getCategoriesList($output, $row['id'], $seprator . ' - ');
}
推荐阅读
- selenium-webdriver - Mac OS M1 上的 Selenium 无法打开 Firefox 浏览器
- firebase - 每个项目的每日写入请求 - 云功能
- python - 在 Python 中以表格形式打印数据
- javascript - 我的 indexOf() 方法有效,但是当涉及到最后一个值时,它停止工作
- apache-kafka - Keberized Kafka 客户端登录异常
- azure - 如何查看 Azure Synapse 中的物化视图数据存储和维护成本?
- react-native - 如何在本机反应中将滑块连接到 redux?
- python - 在图像 OpenCV 和 Python 中查找所有多边形
- javascript - 正则表达式匹配字符串中的变量标识符、函数标识符、函数参数和类名
- reactjs - React 三纤维向 obj 模型添加纹理