博客园  :: 联系 :: 管理

ASP.NET提供了三种后台输出JS的方式

Posted on 2011-08-02 11:09  独孤雁  阅读(184)  评论(0编辑  收藏  举报

ASP.NET提供了三种后台输出JS的方式:

  一、后台输出已有js文件

  首先创建 js文件testjs.js

以下是代码片段:
 if (!Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "keys"))//判断keys是否已注册过
  {
  Page.ClientScript.RegisterClientScriptInclude("keys", "testjs.js");
  }

  二、输出js代码块

以下是代码片段:
 string scriptstrs = "";//此处只作为演示,如代码需多次拼接应采用StringBuilder方式
  scriptstrs += "function test(str)";
  scriptstrs+="{alert(str);}";
  if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "keys"))
  {
  Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "keys", scriptstrs, true);
  }

  三、 输出一次性使用的js代码

以下是代码片段:
 string scriptstrs = "";
  if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(),"welcome"))
  {
  Page.ClientScript.RegisterStartupScript(this.GetType(), "welcome", scriptstrs);
  }

  此外,运用Response.Write(" "); 方式也可输出简单js代码,但我个人不提倡采用此种方式。因为在以前开发中遇到有些情况下此种方式会导致弹出提示信息后页面字号改变的现象,所以安全起见建议采用上述三种方式。