【问题标题】:select box show another based on what selected选择框根据所选内容显示另一个
【发布时间】:2013-09-02 21:11:04
【问题描述】:

当用户从主选择框中选择时,我试图通过选择框显示更多选项。我已经为选择框添加了display:none,只有当用户从主选择框中选择选项时才会显示。

谁能帮助我使用 jquery 或 javascript仅适用于第一个选项

 .sub{display:none;}

 <select> <!--This is main selectbox.-->
 <option value="">Select</option>
 <option>ONE</option>
 <option>two</option>
 <option>three</option>
 <option>four</option>
 <option>five</option>
 </select>


 <select class="sub"><!--another selectbox for option one.-->
 <option>test1</option>
 <option>test1</option>
 </select>

 <select class="sub"><!--another selectbox for option two.-->
 <option>test2</option>
 <option>test2</option>
 </select>


 <select class="sub"><!--another selectbox for option three.-->
 <option>test3</option>
 <option>test3</option>
 </select>


 <select class="sub"><!--another selectbox for option four.-->
 <option>test4</option>
 <option>test4</option>
 </select>


 <select class="sub"><!--another selectbox for option five.-->
 <option>test5</option>
 <option>test5</option>
 </select>

【问题讨论】:

    标签: javascript jquery html css drop-down-menu


    【解决方案1】:

    DOM Select Element 有selectedIndex 属性,它指定了被选Option 的索引,通过使用jQuery 的.eq() 方法,这个属性和监听change 事件你可以从jQuery 基于索引的集合中选择目标选择元素:

    var $sub = $('select.sub');
    
    $('select').first().change(function() {    
        $sub.hide();
        // If the first option is not selected
        if (this.selectedIndex > 0)
           $sub.eq(this.selectedIndex - 1).show();
    });
    

    http://jsfiddle.net/7CmYj/

    【讨论】:

    • 感谢完美。如果我想通过更改类来根据第二个选择框上选择的内容创建另一个第三个选择框,我可以做同样的事情吗?
    • @amdvb 不客气,是的,如果您知道自己在做什么,那么一切有意义的事情都是可能的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多