将变量 ClientID 传递给 JavaScript 函数以显示/隐藏 DIV

Passing variable ClientID to JavaScript function to show/hide DIV

本文关键字:显示 隐藏 DIV 函数 JavaScript ClientID 变量      更新时间:2023-09-26

我有一个带有 3 个 HTML 按钮的 ASPX 页面,它们都触发相同的 JS 函数以及单个参数。按钮传递 DIV 的 ID,函数显示/隐藏该 DIV。

如果它是每个按钮的一个函数(具有硬编码值),我可以让它工作,但我似乎无法弄清楚如何使它成为函数接受 ClientID 作为参数。

<button id="a_button" onclick="Show_Hide_Display('<%=section_a.ClientID%>');return false">Section A</button>
<button id="b_button" onclick="Show_Hide_Display('<%=section_b.ClientID%>');return false">Section B</button>
<button id="c_button" onclick="Show_Hide_Display('<%=section_c.ClientID%>');return false">Section C</button>
<script type="text/javascript">
    function Show_Hide_Display(divID) {
        var div = document.getElementById(divID);
        if (div.style.display == "" || div.style.display == "block") {
            div.style.display = "none";
        }
        else {
            div.style.display = "block";
        }
        return false;
    }
</script>

我已经尝试了包括上述在内的几件事,结果是:

TypeError: Div is null

编辑:

这是构建将显示/隐藏的 DIV 的地方(在包含按钮的 DIV 下方的 DIV 中,在 JavaScript 上方)。

<div id="pdp_section_a_intro" class="pdp_section_a_intro" runat="server">
    <h2>Section A</h2>
    <div id="section_a" Class="pdp_section" runat="server" style="display:none;">
        <asp:PlaceHolder ID="pdp_subssections_a_ph" runat="server"></asp:PlaceHolder>
    </div>
</div>
<div id="pdp_section_b_intro" class="pdp_section_b_intro" runat="server">
    <h2>Section B</h2>
    <div id="section_b" Class="pdp_section" runat="server">
        <asp:PlaceHolder ID="pdp_subssections_b_ph" runat="server"></asp:PlaceHolder>
    </div>
</div>
<div id="pdp_section_c_intro" class="pdp_section_c_intro" runat="server">
    <h2>Section C</h2>
    <div id="section_c" Class="pdp_section" runat="server">
        <asp:PlaceHolder ID="pdp_subssections_c_ph" runat="server"></asp:PlaceHolder>
    </div>
</div>

使用任何服务器端控件时,不能在内部嵌入服务器端代码。你能试试下面吗,

在 ASPX 页中,

    <asp:Button ID="btn1" runat="server" Text="Button 1" />
    <asp:Button ID="btn2" runat="server" Text="Button 2" />
    <asp:Button ID="btn3" runat="server" Text="Button 3" />

在代码隐藏中,

    btn1.Attributes.Add("onclick", "Show_Hide_Display('" & section_a.ClientID & "');return false;")
    btn2.Attributes.Add("onclick", "Show_Hide_Display('" & section_b.ClientID & "');return false;")
    btn3.Attributes.Add("onclick", "Show_Hide_Display('" & section_c.ClientID & "');return false;")