2016-06-01 154 views
2

我有一个包含7个选项的下拉列表。用户选择的每个选项必须在其正下方的文本区域中填写说明。我想要实现的是当选择一个选项时显示适当的div并隐藏其他。这是我到目前为止根据下拉菜单选择隐藏并显示div

$(document).ready(function() { 
     $("#define-labelling").hide(); 
     ... hide the remaining divs here 

$("#ProjectStatus").change(function() { 
      var selectedValue = ""; 
      $("#ProjectStatus option:selected").each(function() { 
       selectedValue += $(this).val(); 
       if (selectedValue === "Define (Labelling)") { 
        $("#define-labelling").fadeIn("slow"); 
       } 
       ... More if statements here for the other divs 
      }); 
     }); 
    }); 
}); 

我的问题是,是否有更干净的方式去做这件事?因为目前我有多个if语句并隐藏并显示相应的div变得有点难看。

更新以下@Mairaj答案

function showDiv() { 
    var divID = $("#ProjectStatus option:selected").attr("data-div"); 
    alert(divID); //this comes as undefined 
    $("#" + divID).show(); 
    $("#" + divID).siblings().hide(); 
} 

我已经添加了两个div为:

<div class="form-group" id="Define (Labelling)" style="display: none;"> 
@Html.LabelFor(model => Model.LabellingInfo, htmlAttributes: new { @class = "control-label col-md-2" }) 
<div class="col-md-10"> 
    @Html.TextAreaFor(model => Model.LabellingInfo, htmlAttributes: new { @class = "form-control description" }) 
</div> 
</div> 
<div class="form-group" id="Analysis (Root Cause)" style="display:none;"> 
@Html.LabelFor(model => Model.RootCauseInfo, htmlAttributes: new { @class = "control-label col-md-2" }) 
<div class="col-md-10"> 
    @Html.TextAreaFor(model => Model.RootCauseInfo, htmlAttributes: new { @class = "form-control description" }) 
</div> 

+0

也许你可以添加一个类'none'和'.none {显示:无;}',如果发生变更,然后'$(#ProjectStatus).addClass( '无')'和'$(” #define-labeling“).. removeClass('none')' – gdreamlend

+0

@gdreamlend请问您能详细说明一下吗? – Code

+0

您在选择选项中显示的内容是否已修复。 –

回答

2

您可以添加自定义属性(data-div)到dropdown的每个option这将是divID将被显示。

<div id="divMain" > 
    <div id="Div1">Div1</div> 
    <div id="Div2" style="display:none">Div2</div> 
    <div id="Div3" style="display:none">Div3</div> 
</div> 


<select id="ddlOption" onchange="showdiv()"> 
    <option value="Div1" data-div="Div1">Div1</option> 
    <option value="Div2" data-div="Div2">Div2</option> 
</select>  

这里是jQuery代码将根据所选option

function showdiv() 
{ 
    var divID = $("#ddlOption option:selected").attr("data-div"); 
    divID = divID.replace(" ",""); 
    $("div[id$='" + divID+"']").show(); 
    $("div[id$='" + divID + "']").siblings().hide(); 
} 
+0

感谢您的答案,我将如何有'data-div'选项?因为我的'