根据下拉列表中的选择隐藏和显示面板

时间:2013-03-07 20:13:41

标签: javascript html

我创建了一个脚本,该脚本应显示和隐藏一些项目,具体取决于从5个下拉列表中选择的相同选项。此下拉列表中的此选项完全相同。所以我只是检查我的解决方案是否可以简化

HTML:

<label for="ddlGift1">Gift #1</label>
         <asp:DropDownList runat="server" ID="ddlGift1" AutoPostBack="true" AppendDataBoundItems="True" ClientIDMode="Static" > 
             <asp:ListItem Value="--" Text="--" />
         </asp:DropDownList>   
<label for="ddlGift2">Gift #2</label>
         <asp:DropDownList runat="server" ID="ddlGift2" AutoPostBack="true" AppendDataBoundItems="True" ClientIDMode="Static" > 
             <asp:ListItem Value="--" Text="--" />
         </asp:DropDownList>
<label for="ddlGift3">Gift #3</label>
         <asp:DropDownList runat="server" ID="ddlGift3" AutoPostBack="true" AppendDataBoundItems="True" ClientIDMode="Static" > 
             <asp:ListItem Value="--" Text="--" />
         </asp:DropDownList>   
<label for="ddlGift4">Gift #4</label>
         <asp:DropDownList runat="server" ID="ddlGift4" AutoPostBack="true" AppendDataBoundItems="True" ClientIDMode="Static" > 
             <asp:ListItem Value="--" Text="--" />
         </asp:DropDownList>     
<label for="ddlGift5">Gift #5</label>
         <asp:DropDownList runat="server" ID="ddlGift5" AutoPostBack="true" AppendDataBoundItems="True" ClientIDMode="Static" > 
             <asp:ListItem Value="--" Text="--" />
         </asp:DropDownList> 

JS:

   var gift1 = $('#ddlGift1');
   var gift1 = $('#ddlGift1');
   var gift2 = $('#ddlGift2');
   var gift3 = $('#ddlGift3');
   var gift4 = $('#ddlGift4');
   var gift5 = $('#ddlGift5');

   showHide();
   gift1.change(function () {
    showHide();
});
gift2.change(function () {
    showHide();
});
gift3.change(function () {
    showHide();
});
gift4.change(function () {
    showHide();
});
gift5.change(function () {
    showHide();
});
 function showHide() {
var gift1 = $('#ddlGift1');
var gift2 = $('#ddlGift2');
var gift3 = $('#ddlGift3');
var gift4 = $('#ddlGift4');
var gift5 = $('#ddlGift5');
var vsity = $('#shvarsity');



if ((gift1.children("option:selected").text())||(gift2.children("option:selected").text())||(gift3.children("option:selected").text())||(gift4.children("option:selected").text())||(gift5.children("option:selected").text()) == "Varsity Club")
{

    vsity.show();

} else {

    vsity.hide();
}

}

1 个答案:

答案 0 :(得分:0)

为所有“gift”元素添加一个类,例如

<asp:DropDownList runat="server" id="ddlGift1" class="gift" AutoPostBack="true" AppendDataBoundItems="True" ClientIDMode="Static" > 
    <asp:ListItem Value="--" Text="--" />
</asp:DropDownList>

然后JS会看起来像

var gifts = $('.gift');
showHide();

gifts.change(function () {
    showHide();
});

function showHide() {
for (i in gifts) {
    if (gifts[i].children("option:selected").text() == "Varsity Club")
    {
        vsity.show();
    } else {
        vsity.hide();
    }
}
}