【问题标题】:Choose which select option is visible选择可见的选择选项
【发布时间】:2013-11-19 03:58:19
【问题描述】:

我在 HTML 中有一个选择,它是动态生成的。

页面加载时,我想让选择框在页面加载时有一个可变的默认选项,而不必更改选择列表的顺序。

当我动态生成页面时,我无法通过设置value 属性来完成这项工作。无论value 属性如何,它始终是可见的最高值。

我还希望能够在文档加载后通过 jQuery 进行更改。

这可能吗?

<select class="form-control input-lg" tabindex=1 id="instrument-select" 
                      name="instrument" value="<?php echo $instrument->slug; ?>">
    <?php foreach ($instrument_list as $instrument): ?>
        <option value="<?php echo $instrument['slug']; ?>">
                              <?php echo $instrument["name"]; ?>
        </option>
    <?php endforeach; ?>
</select>

【问题讨论】:

标签: javascript jquery html html-select


【解决方案1】:

我认为你只需要这样做

<select class="form-control input-lg" tabindex=1 id="instrument-select" name="instrument">
    <?php foreach ($instrument_list as $instrument): ?>
        <option value="<?php echo $instrument['slug']; ?>" <?php echo $instrument->slug==$instrument['slug']?'selected="selected"':''; ?>><?php echo $instrument["name"]; ?></option>
    <?php endforeach; ?>
</select>


永远不要向 select 添加 value 属性,它应该存在于每个单独的 option 上,并且只需要将 selected 设置为所需的选项。

【讨论】:

    【解决方案2】:

    动态创建select html时,将'selected'属性添加到你想要选择的option元素中;

    <option value='firstOption'>firstOption</option>
    <option value='someOption' selected>Some Option</option>  <!-- this one will be selected -->
    <option value='thirdOption'>thirdOption</option>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 2016-06-30
      • 2014-05-17
      • 1970-01-01
      • 2018-04-12
      • 1970-01-01
      • 2020-02-28
      相关资源
      最近更新 更多