JavaScript学习笔记(三)—在ASP.NET网页中集成JavaScript

JavaScript是Web应用程序客户端的主流编程语言,在实际项目中经常需要向ASP.NET网页中动态添加JavaScript代码。

1.在控件声明中直接添加JavaScript代码

    <asp:Button ID="Button2" runat="server"   onmouseover="this.style.color='Red'" οnmοuseοut="this.style.color='black'" Text="会变色的按钮"/>

   onmouseover、onmouseout不是Button控件的属性,而是HTML元素的事件属性。当HTML页面呈现时,ASP.NET会原封不动地将它不能解析的属性发给浏览器客户端。

2.使用Control.Attributes.Add方法添加JavaScript代码

    <script type="text/javascript">
       //实现字符计数器的JavaScript函数
       function inputcounter(inputid,counterid,maxlength)
      {
           var txt=document.getElementById(inputid);
           var counterid=document.getElementById(counterid);
           if((txt!=null) && (counterid!=null))
           {
           counterid.value=(parseInt(maxlength)-txt.value.length).toString();
           }
      }
    </script>      

    protected void Page_Load(object sender, EventArgs e)
    {
        //动态“组装”JavaScript脚本,
        //inputcounter()是一个JavaScript函数,定义在页面的<head>元素内
        string script = "inputcounter('{0}','{1}',{2});";
        script = string.Format(script, txtInput.ClientID, txtCount.ClientID, 2000);
        //将JavaScript脚本附加到文本框控件的属性上
        txtInput.Attributes.Add("onkeyup",script);
    }


3.使用RegisterStartupScript等系列方法

   Page类提供了一个ClientScript对象,它有一系列的方法向ASP.NET页面动态注入JavaScript代码

     <input id="HtmlButton1" type="button" runat="server" value="我是一个普通的HTML按钮,现在没有任何的响应代码" />
    <hr />
    <asp:Button ID="btnRegisterJavaScript" runat="server" Text="给网页动态注入JavaScript代码"
        OnClick="btnRegisterJavaScript_Click" /> 

    protected void btnRegisterJavaScript_Click(object sender, EventArgs e)
    {
        //要加入的JavaScript代码块
        string script = "  function SayHello()  {alert(\"Hello\"); }";

        //以下两句中任何一句都可以向页面中添加的JavaScript代码块
        //请通过生成的HTML网页源码找出这两个方法的差异
        //ClientScript.RegisterClientScriptBlock(this.GetType(), "SayHello", script,true);
        ClientScript.RegisterStartupScript(this.GetType(), "SayHello", script, true);
       
        HtmlButton1.Value = "我是一个普通的HTML按钮,现在动态挂接上了的响应代码";
        //给按钮添加事件响应函数
        HtmlButton1.Attributes["onclick"] = "SayHello();";
    }

3.1 RegisterClientScriptBlock、RegisterStartupScrip区别

      这两个方法在客户端呈现的代码位置不同:RegisterClientScriptBlock添加的JavaScript代码出现在页面<body>元素内部,往往与其他HTML代码混杂在一起,因此这些代码可能无法访问页面上的所有HTML元素;而RegisterStartupScript添加的JavaScript代码出现在<body>元素的最后部分。

本文主要参考了金旭亮先生的《Asp.Net程序设计教程》。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值