我在这里有一个绝对的头脑空白。基本上我所做的就是创建一个迷你文章管理器。可以将每篇文章分配到以下类别之一,这些类别在选择下拉列表中定义。
当我去编辑文章时,我从数据库中检索了数据并填充了输入和textarea。
我现在要做的是将selected
属性应用于与文章类别匹配的选项。以下是我所做的,我相信你会同意这是一个糟糕的方法:
<?php if($category == 'Design') { ?>
<option value="Design" selected>Design</option>
<option value="Development">Development</option>
<option value="Other">Other</option>
<?php } elseif($category == 'Development') { ?>
<option value="Design">Design</option>
<option value="Development" selected>Development</option>
<option value="Other">Other</option>
<?php } else { ?>
<option value="Design">Design</option>
<option value="Development">Development</option>
<option value="Other" selected>Other</option>
<?php } ?>
问题是,如何根据文章类别实施一种更动态的方法将selected
属性应用于<option>
?
答案 0 :(得分:4)
为什么不在数组中定义类别,然后循环它:
<?php
$cats = array('Design', 'Development', 'Other');
foreach($cats as $cat)
{
$selected = ($cat == $category) ? ' selected="selected"' : '';
echo '<option value="'.$cat.'"'.$selected.'>'.$cat.'</option>';
}
?>
当然,这还有一个额外的好处,如果你需要添加一个新类别,只需将它添加到数组中。
答案 1 :(得分:3)
将类别放入数组中,然后执行以下操作:
$categories = Array("Foo", "Bar", "Baz");
$preselected_category = "Bar";
foreach ($categories as $category) {
$html = htmlspecialchars($category);
$selected = "";
if ($category == $preselected_category) {
$selected = "selected";
}
?> <option value="<?=$html?>" <?=$selected?>> <?=html?> </option> <?php
}
答案 2 :(得分:2)
使用它如下
<option value="Design" <?=($category == 'Design')?'selected':''?> >Design</option>
<option value="Development" <?=($category == 'Development')?'selected':''?>>Development</option>
<option value="Other" <?=($category == 'Other')?'selected':''?>>Other</option>
答案 3 :(得分:1)
这个怎么样?
<option value="Design" <? if($category == 'Design') { echo 'selected';} ?>>Design</option>
<option value="Development" <? if($category == 'Development') { echo 'selected';} ?>>Development</option>
<option value="Other" <? if($category == 'Othe') { echo 'selected';} ?>>Other</option>
答案 4 :(得分:0)
您可以使用数组来存储类别,并循环显示它以生成您的html。
<?php
$categories = array(
'Design',
'Development',
'Other',
);
$category = 'Design';
foreach($categories as $cat) {
$selected = ($category == $cat);
$selcode = ($selected ? ' selected' : '');
$html = '<option value="'.$cat.'"'.$selcode.'>'.$cat.'</option>';
echo $html . PHP_EOL;
}