[英]Div element hide and show
我有一个隐藏的div元素。
<div class= "CTL" id="CTL" runat="server" style="display:none">
<p class ="divider">
CTL
</p>
<asp:Button ID="CTL_button" runat="server" Text="View CTL"
onclick="CTL_button_Click" />
</div>
我试图根据页面Load:-返回的SQL值使div元素显示或保持隐藏。
window.onload= function show_CTL() {
if("<%=_CurrentUser.IsCTL%>" == "True"){
document.getElementById('CTL').style.display ="block";
}
else{
// document.getElementById('CTL').style.display ="none";
}
但是div元素仍然显示,无论返回的值如何。
似乎只执行了循环的真正部分...
使用display:none将div放在第一位
<div class= "CTL" id="CTL" style="display:none" runat="server">
<p class ="divider">
CTL
</p>
<asp:Button ID="CTL_button" runat="server" Text="View CTL"
onclick="CTL_button_Click" />
</div>
然后你可以用
document.getElementById('CTL').style.display ="block";
ASP.NET正在更改ID,这就是为什么必须使用元素的clientID的原因。
document.getElementById("<%= CTL.ClientID %>").style.display = "block";
visible
和display
是2个不同的CSS属性,
您先设置了“ visible
,但随后更改了display
,
您应该更改可见而不是显示,因为您可以首先使用显示而不是可见。
在JavaScript中将条件强制转换为Boolean
,您可以这样做:
window.onload = function show_CTL() {
var el = document.getElementById('CTL');
if(Boolean("<%=_CurrentUser.IsCTL%>") && el){
el.style.display = "block";
}
else{
el.style.display = "none";
}
}
如果布尔对象没有初始值,或者传递的值是以下值之一:
0
-0
null
""
false
undefined
NaN
该对象设置为false。 对于任何其他值,它都设置为true(即使使用字符串“ false”)!
现在我想知道,为什么不简单地将条件添加到visible
属性中呢?
<div class="CTL" id="CTL" runat="server" visible=<%=_CurrentUser.IsCTL%>></div>
这样就不需要JavaScript。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.