关于ASP.net中服务器控件的脚本问题

     最近在做一个学术期刊的投稿子模块,其中涉及到div的隐藏和显示,具体是要在后台获取数据然后决定div的隐藏或者是显示以及checkbox的选中或者是未选中状态。

想了好多自以为是的方法,接二连三地失败了

下面给出正确的思路和方法,也算是给自己积累点东西

1,前台代码

代码
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>测试</title>
    
<style type="text/css">
    #div_box
    
{
        width
:300px;
        border
:solid 1px red;
    
}
    
</style>
    
<script type="text/javascript">
        
function show()
        {
            
var cbox = document.getElementById('cb');
            
var div_b = document.getElementById('div_box');
            
if(cbox.checked)
            {
                div_b.style.display 
= "block";
            }
            
else
            {
                div_b.style.display 
= "none";
            }
        }
    
</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        选项1…………
<br />
        
<br />
        选项2…………
<br />
        
<br />
        …………………………
<br />
        
<br />
        
<input type ="checkbox" id="cb" runat="server" onclick="show()" /><label for="cb">附加选项</label>
    
</div>
    
<div id="div_box" runat="server">
        第二作者姓名:
<asp:TextBox ID="txt_authorName2" runat="server"></asp:TextBox><br />
        
<br />
        第二作者性别:
<asp:TextBox ID="txt_authorSex2" runat="server"></asp:TextBox><br />
        
<br />
        第二作者年龄:
<asp:TextBox ID="txt_authorAge2" runat="server"></asp:TextBox>
    
</div>
    
</form>
</body>
</html>

 2,后台代码

代码
public partial class _Default : System.Web.UI.Page 
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (!IsPostBack)
        {
            
//获取是否有第二作者的信息…………
            
//设置cb.Checked = true or false

            
if (cb.Checked)
            {
                
//div_box.Visible = true;//这样写是可以的,但是当执行js脚本(document.getElementById('div_box')为null)就会出现"缺少对象"错误
                div_box.Attributes.Add("style""display:block");
            }
            
else
            {
                
//div_box.Visible = false;//同上
                div_box.Attributes.Add("style""display:none");
            }
        }
    }
}

       上面的代码有两处需要注意,一处就是后台的代码,注释掉的那两句。当初想当然以为这样可以,后来发现当点击checkbox按钮的时候,会出现脚本错误,说“缺少对象”。。还一处就是div_box的样式要写在一个样式表中或者在<head></head>之间嵌入样式,否者样式会丢失,因为在Page_Load事件中重写了style,除非后台两句代码改成如下形式。

div_box.Attributes.Add("style""display:block;width:300px;border:solid 1px red");

div_box.Attributes.Add(
"style""display:none;width:300px;border:solid 1px red");

但说实话,这并不是一种好的方法。

以后自己要切记切记。。。。。

posted @ 2010-03-21 17:05  爱生活,爱GIS  阅读(348)  评论(0编辑  收藏  举报