html选择选项SELECTED [英] html select option SELECTED

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

问题描述

我在php中有

I have in my php

$sel = "
    <option> one </option>
    <option> two </option>
    <option> thre </option>
    <option> four </option>
";

假设我有一个内联网址= site.php?sel = 1

let say I have an inline URL = site.php?sel=one

如果我没有在变量中保存这些选项,我可以通过这种方式来使其中一个选项成为SELECTED,其中值等于 $ _ GET [sel]

if I didn't saved those options in a variable, I can do it this way to make one of the option be SELECTED where value is equal to $_GET[sel]

<option <?php if($_GET[sel] == 'one') echo"selected"; ?> > one </option>
<option <?php if($_GET[sel] == 'two') echo"selected"; ?> > two </option>
<option <?php if($_GET[sel] == 'three') echo"selected"; ?> > three </option>
<option <?php if($_GET[sel] == 'four') echo"selected"; ?> > four </option>

但问题是,我需要将这些选项保存在一个变量中,因为我有很多选项我需要多次调用该变量。

but the problem is, I need to save those options in a variable because I have a lot of options and I need to call that variable many times.

有没有办法让选项被选中,其中 value = $ _GET [sel]

Is there a way to make that option be selected where value = $_GET[sel] ?

推荐答案

只需使用数组选项,即可查看当前选中的选项。 p>

Just use the array of options, to see, which option is currently selected.

$options = array( 'one', 'two', 'three' );

$output = '';
for( $i=0; $i<count($options); $i++ ) {
  $output .= '<option ' 
             . ( $_GET['sel'] == $options[$i] ? 'selected="selected"' : '' ) . '>' 
             . $options[$i] 
             . '</option>';
}

旁注:我将定义一个值为某种id对于每个元素,否则当两个选项具有相同的字符串表示形式时,您可能会遇到问题。

这篇关于html选择选项SELECTED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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