选择选项“已选择"被选择为“已选择".属性 [英] Selection option "selected" attribute

查看:113
本文介绍了选择选项“已选择"被选择为“已选择".属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里完全没有头脑.基本上,我所做的就是创建一个迷你文章管理器.可以将每个文章分配给以下类别之一,这些类别在选择下拉列表中定义.

I've got an absolute mind blank here. Basically what I've done is created a mini Article Manager. Each article can be assigned to one of the following categories which are defined in a select dropdown.

  • 设计
  • 发展
  • 其他

当我去编辑文章时,我已经从数据库中检索了数据,并填充了输入和文本区域.

When I go to edit an article, I have retrieved the data from the database and populated the inputs and textarea.

我现在想要做的是将selected属性应用于与文章类别匹配的选项.以下是我所做的事情,我相信您会认为这是一种错误的方法:

What I'm now trying to do is apply the selected attribute to the option that matches the article category. The following is what I have done, which I'm sure you will agree is a bad approach:

<?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>的动态方法呢?

So the question being is, how can I implement a more dynamic method of applying the selected attribute to an <option> based on the article category?

推荐答案

为什么不只是在数组中定义类别并对其进行循环:

Why not just define the categories in an array, and loop it:

<?php
$cats = array('Design', 'Development', 'Other');
foreach($cats as $cat)
{
    $selected = ($cat == $category) ? ' selected="selected"' : '';
    echo '<option value="'.$cat.'"'.$selected.'>'.$cat.'</option>';
}
?>

当然,这样做还有其他好处,如果需要添加新类别,只需将其添加到数组中即可.

Of course, this has the added benefit that in case you need to add a new category, just add it to the array.

这篇关于选择选项“已选择"被选择为“已选择".属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆