javascript – 使用JQuery显示/隐藏控件,具体取决于下拉列表选择的值

我正在尝试使用 JQuery根据下拉菜单中选定的索引显示/隐藏div标签,但它无法正常工作.任何帮助将不胜感激.

谢谢.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="drop_down_test.WebForm1" %>

<form runat="server" ID="frmReport">
    <asp:DropDownList ID="ddlReports" OnChange="ShowHide()" AutoPostBack="true" runat="server" 
        onselectedindexchanged="ddlReports_SelectedIndexChanged">
        <asp:ListItem Text="Please Select Report" Value="Default" />
        <asp:ListItem Text="Report 1" Value="ReportValue1" />
        <asp:ListItem Text="Report 2" Value="ReportValue2" />
    </asp:DropDownList>
    <br />
    <br />
    <div id="Report1Section">
        <asp:Label ID="lblReport1" Text="This is for Report 1" runat="server" />
    </div>
    <br />
    <div id="Report2Section">
        <asp:Label ID="lblReport2" Text="This is for Report 2" runat="server" />
    </div>
</form>

<script language="JavaScript" type="text/javascript" src="~/Scripts/jquery-1.4.1.js"></script>

<script type="text/javascript">
    function ShowHide() {
        var ddlSelectedIndex = ('#<%= ddlReportName.ClientID %>').get(0).selectedIndex;

        switch (ddlSelectedIndex) {
            case 1:
                $('#Report1Section').show('slow');
                $('#Report2Section').hide('fast');
                break;
            case 2:
                $('#Report1Section').hide('fast');
                $('#Report2Section').show('slow');
                break;
        }
    }
</script>

解决方法

使用像@Victor这样的类说. ASP.Net版本< 4将弄乱ID. 利用可以将多个类应用于HTML元素的事实.这允许您分组内容.例如.所有可隐藏的reportdivs.

<div id="Report2Section" class="Report2 reportDiv">
      <asp:Label ID="lblReport2" Text="This is for Report 2" runat="server" />
  </div>

然后使用列表项的值中的名称(已删除的空格)来获取您需要显示的div的ID.您可以在页面的ready(…)事件中将事件连接到JQuery.

< asp:DropDownList ID =“ddlReports OnChange =”ShowHide()“runat =”server“
的AutoPostBack = ‘真正的’
[像@SeanTaylor那样从下拉列表中取出自动回复 – 你想要改变你的javascript代码而不是ASP.Net回发到服务器机制.]

onselectedindexchanged = “ddlReports_SelectedIndexChanged”
[通过nu-skool,JQuery方式(见下文)]将您的活动连接起来]
>
        

< asp:ListItem Text =“Report 1”Value =“Report1 [删除值中的空格] />
        
    

然后,您可以将所有reportdiv上的slideDown作为一个组调用,然后通过下拉列表中的ID调用所需的slideUp:

$(document).ready(function(){//there is a more modern way of writing this line.
    $('.ddlReports').change(function(){//JQuery style of wiring events up  
            $('.reportDiv').slideUp();//takes care of whichever one is showing (if any).
            $('#' + $(this).val() + "Section").slideDown();
    });
});

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...