【发布时间】:2016-03-03 18:49:07
【问题描述】:
我有一个带有 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 下方、JavaScript 上方的 DIV 中)。
<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>
【问题讨论】:
-
不是在函数“Show_Hide_Display”中传递客户端 ID,而是为 div 传递像 1 或 2 或 3 这样的标志。并且在函数检查条件中 if 1 然后 document.getElementById('') 等等第四个。它肯定会起作用
-
我想这可以工作,只要你知道会有多少 DIV。该项目的下一步是动态生成 DIV 和按钮,因此该函数需要能够在事先不知道它会影响的 DIV 的情况下处理这些。
-
是的,当我看到您的 HTML 时,您是对的,我认为它是静态的。这就是我给你这个解决方案的原因
标签: javascript html