如何隐藏/显示<面板>使用jquery

How do I hide/show a <panel> using jquery?

本文关键字:lt 面板 gt jquery 使用 显示 何隐藏 隐藏      更新时间:2023-09-26

我正在努力在点击按钮时显示一个面板(包含两个标签,在页面加载时隐藏),但没有成功。

当我点击一个按钮(id=Button1)时,它应该会显示一个面板(id=anspanel),但事实并非如此。相反,它保持原样,即点击按钮时不会发生任何事情。我不知道为什么。看看我的代码。告诉我哪里犯了错误,解决方法是什么。

.aspx:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Student_Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.8.3/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.3/jquery-ui.js"></script>
<script type="text/javascript">
    var currentTab = 0;
    $(function () {
        $("#tabs").tabs({
            select: function (e, i) {
                currentTab = i.index;
            }
        });
    });
    $("#btnNext").live("click", function () {
        var tabs = $('#tabs').tabs();
        var c = $('#tabs').tabs("length");
        currentTab = currentTab == (c - 1) ? currentTab : (currentTab + 1);
        tabs.tabs('select', currentTab);
        $("#btnPrevious").show();
        if (currentTab == (c - 1)) {
            $("#btnNext").hide();
        } else {
            $("#btnNext").show();
        }
    });
    $("#btnPrevious").live("click", function () {
        var tabs = $('#tabs').tabs();
        var c = $('#tabs').tabs("length");
        currentTab = currentTab == 0 ? currentTab : (currentTab - 1);
        tabs.tabs('select', currentTab);
        if (currentTab == 0) {
            $("#btnNext").show();
            $("#btnPrevious").hide();
        }
        if (currentTab < (c - 1)) {
            $("#btnNext").show();
        }
    });
    $(function () {
        //$("#Panel2").hide();
        document.getElementById('form1').onsubmit = function () {
            return false;
        }//Avoid Reloading
        $("#Button1").click(function () {
            if ($('#anspanel').is(":hidden")) {
                $('#anspanel').show();
       
            }
            else {
                $('#anspanel').hide();
            }
            if ($("#Button1").val() == "Show Answer") {
                $("#Button1").val("Hide Answer");
            } else {
                $("#Button1").val("Show Answer");
            }
       
        });
       
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="tabs">
    <ul>
        <li><a href="#tabs-1">Tab 1</a></li>
        <li><a href="#tabs-2">Tab 2</a></li>
        <li><a href="#tabs-3">Tab 3</a></li>
        <li><a href="#tabs-4">Tab 4</a></li>
        <li><a href="#tabs-5">Tab 5</a></li>
    </ul>
    <div id="tabs-1">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
        <asp:Panel ID="Panel1" runat="server">
            <asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'></asp:Label>
            <br />
            <br />
            <br />
           <span>A-</span> <asp:Label ID="Label2" runat="server" Text='<%#Eval("Option1")%>'></asp:Label>
            <br />
            <br />
            <span>B-</span> <asp:Label ID="Label3" runat="server" Text='<%#Eval("Option2")%>'></asp:Label>
            <br />
            <br />
            <span>C-</span> <asp:Label ID="Label4" runat="server" Text='<%#Eval("Option3")%>'></asp:Label>
            <br />
            <br />
            <span>D-</span> <asp:Label ID="Label5" runat="server" Text='<%#Eval("Option4")%>'></asp:Label>
            <br />
            <br />
            &nbsp;&nbsp;
            <asp:Button ID="Button1" runat="server" Text="Show Answer"  />
            <br />
            <asp:Panel id="answerspanel" runat="server">
                <span>Correct Answer is :-</span><asp:Label ID="Label6" runat="server" Text='<%#Eval("CorrectAns")%>'></asp:Label>
                <br />
                <br />
                <asp:Label ID="Label7" runat="server" Text='<%#Eval("Explanation")%>'></asp:Label>
            </asp:Panel>
        </asp:Panel>
        <br />
        <br />
                 </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
       
    </div>
    <div id="tabs-2">
        Tab 2 Content
    </div>
    <div id="tabs-3">
        Tab 3 Content
    </div>
     <div id="tabs-4">
        Tab 4 Content
    </div>
     <div id="tabs-5">
        Tab 5 Content
    </div>
</div>
<input type="button" id="btnPrevious" value="Previous" style = "display:none"/>
<input type="button" id="btnNext" value="Next" />
    
    </div>
    </form>
</body>
</html>

.aspx.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

public partial class Student_Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GridView1.DataSource = GetData("SELECT top 2 Question, Option1, Option2, Option3, Option4, CorrectAns, Explanation FROM Questions");
        GridView1.DataBind();
        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowType == DataControlRowType.DataRow)
            {
                Panel panel1 = (Panel)row.FindControl("Panel1");
                Panel anspanel = (Panel)panel1.FindControl("answerspanel");
                anspanel.Style.Add("display", "none");
            }
        }
    }
}
private DataSet GetData(string query)
{
    string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                return ds;
            }
        }
    }
}
}

错误:-

Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error: 

Line 24:                     Panel panel1 = (Panel)row.FindControl("Panel1");
Line 25:                     Panel anspanel = (Panel)panel1.FindControl("answerspanel");
Line 26:                     anspanel.Style.Add("display", "none");
Line 27:                 }
Line 28:             }
Source File: e:'Way2Success'Student'Test.aspx.cs    Line: 26 
Stack Trace: 

[NullReferenceException: Object reference not set to an instance of an object.]
Student_Test.Page_Load(Object sender, EventArgs e) in e:'Way2Success'Student'Test.aspx.cs:26
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2952

问题是,在您有Button1的地方,id将被设置为"ct100_ContentPlaceHolder1_Button1",而在"ct100_ContentPlaceHolder1_anspanel"anspanel的地方。

有两种解决方案:

1) 将客户端Id模式设置为静态:对元素进行设置,以便保持静态Id。

Button1anspanel元素都进行此更改。

<asp:Button ID="Button1" ClientIDMode="Static" runat="server" Text="Show Answer" />

<asp:Panel id="anspanel" ClientIDMode="Static" runat="server">

退出的脚本必须运行良好。

2) 更改脚本以使用clientId

$("#<%= Button1.ClientID %>")代替$("#Button1")

$("#<%= anspanel.ClientID %>")代替$("#anspanel")


编辑1:在你提到它只适用于第一个按钮之后,我意识到你有了gridview,你最终会对所有面板使用相同的id,这在Jquery中不太好用。所以这个想法是玩class选择器。以下是我建议您做的一些更改…

 <asp:Panel ID="Panel1" runat="server">
  <asp:Label ID="Label1" runat="server" Text='<%#Eval("Question") %>'>
   ....
   ....
   <asp:Button class="panelButton" runat="server" Text="Show Answer"  />
   <br />
   <asp:Panel class="AnswerPanel" runat="server">

请注意,我已经在按钮和面板中添加了类。此外,我已经删除了身份证,因为这是不必要的。

然后在您的jquery中更改代码如下

$(".panelButton").click(function () {
   var $thisButton = $(this); //save button into a variable
   var $ansPanel = $(this).parent().find('.AnswerPanel'); //save ans panel into a variable
   if ($ansPanel.is(":hidden")) {
      $ansPanel.show();           
   }
   else {
      $ansPanel.hide();
   }
   if ($thisButton.val() == "Show Answer") {
       $thisButton.val("Hide Answer");
   } else {
       $thisButton.val("Show Answer");
   }               
});

要通过jQuery的ID调用asp.net控件,您应该使用以下内容:$("#<%= yourButtonId.ClientID %>")

因此,在您的情况下,请尝试使用$("#<%= Button1.ClientID %>").click();而不是$("#Button1").click()