首页 > 解决方案 > 下拉选择jQuery

问题描述

我正在制作一个下拉列表,并希望在选择 id="residential" 时显示 div class="residential-options",并在选择 id="commercial" 时显示 div class="commercial-options"。

这是我的 HTML:

<div class= "row">
                <select id='building-type'>  
                    <option disabled selected value> -- select an option -- </option>
                    <option id="residential" value="residential" [...]>Residential</option>
                    <option id="commercial" value="commercial " [...]>Commercial</option>
                    <option id="corporate" value="corporate" [...]>Corporate</option>
                    <option id="hybrid" value="hybrid" [...]>Hybrid</option>

                </select>    
            </div>

        

            <div class="residential-options">

                <div id="number-of-apartments" >
                        <label>N. of Apartments *</label>
                        <input [...]>
                </div>                
             
                
                <div id="number-of-basements" >
                    <label>N. of Basements *</label>
                    <input [...]>
                </div>
            
            </div> 

            <div class="commercial-options">

                <div id="number-of-floors" >
                        <label>N. of Floors *</label>
                        <input [...]>
                </div>

这是我的 jQuery:

$("#building-type").change(function() {
    ($('#residential').is(':checked'))
    $('.residential-options').show();
    $('.commercial-options').hide();
    $('.corporate-options').hide();
    $('.hybrid-options').hide()
    });
$("#building-type").trigger("change");

$("#building-type").change(function() {
    ($('#commercial').is(':checked'))
    $('.commercial-options').show();
    $('.residential-options').hide();
    $('.corporate-options').hide();
    $('.hybrid-options').hide()
    });
$("#building-type").trigger("change");

它只显示我点击的 div class="commercial-options" 。谢谢你的帮助!

标签: javascripthtmljquery

解决方案


您的代码可以大大简化,包括删除.trigger()调用。

$("#building-type").change(function() {
    $('div[class*="options"]').hide(); // hide all '*-option' divs
    // Determine which option was selected and display the corresponding div:
    ['residential', 'commercial', 'corporate', 'hybrid'].forEach(function(base){
        if ($('#' + base + ':checked').length) {
            $(`.${base}-options`).show();
        }
    })
})

推荐阅读