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

时间:2016-03-03 10:16:03

标签: javascript html

我有一个带有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>

1 个答案:

答案 0 :(得分:1)

当您使用任何服务器端控件时,您无法在其中嵌入服务器端代码。你能在下面试试吗,

在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" />

在Code Behind中,

    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;")