【问题标题】:Change javascript src attribute from ASP.net Code Behind从 ASP.net 代码背后更改 javascript src 属性
【发布时间】:2012-05-11 08:07:20
【问题描述】:

我正在尝试从代码隐藏文件中更改 JavaScript src。

<script type="text/javascript" runat="server" id="srcSurvey" language="JavaScript" src="mypage.asp?p=2"></script>

当我试图从代码隐藏文件中访问对象属性时,没有可用的 src 选项,我需要将 src 文件放在其他属性中吗?

【问题讨论】:

  • 我认为你将不得不修改页面的 innerhtml...

标签: c# javascript asp.net html


【解决方案1】:

你不能像那样访问src 属性。 HTML 属性可通过.Attributes 集合访问:

srcSurvey.Attributes["src"] = "my/directory/file.js";

【讨论】:

  • 我做不到,编译器试图读取 js 文件,CS1012: Too many characters in character literal,这是怎么回事?
  • 听起来你正试图将实际的 JS 放到 src 中。只需输入指向文件的字符串,就像我在上面所做的那样。
  • 哦,您也可以将文件路径放在单引号而不是双引号中:)
【解决方案2】:

在 Head html 标记中从 ASP.net Code Behind 更改 javascript src

// this is the name of the file, it could be any name, but because
// you need it dynamic I add the number at the end.
string jsFileName = string.Format("mypage.asp?p={0}", 1);

// we add a HtmlGenericControl with the tag script (this will work for a
// css also, you just need to change script for LINK, and src for href) 
HtmlGenericControl linkDynamicJavascriptFile = new HtmlGenericControl("script");
// and the you add the relative client url of the resource
linkDynamicJavascriptFile.Attributes.Add("src", 
    ResolveClientUrl("~/" + jsFileName));
// just adding the type attribute, not necesary in html5
linkDynamicJavascriptFile.Attributes.Add("type", "text/javascript");
// we add the script html generic control to the Page Header and we're done
Page.Header.Controls.Add(linkDynamicJavascriptFile);

上一个答案

ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
    "stackoverflow", 
    "<script type=\"text/javascript\" src=\"mypage.asp?p=2\"></script>", false);

只需将包含脚本标记的硬编码字符串更改为动态字符串即可。

例如:

string code = string.Empty;
var pageNumber = PageRepository.GetPageAsString(); // get page number
code = string.Format("<script type=\"text/javascript\" src=\"mypage.asp?p={0}\"></script>", pageNumber);

ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"stackoverflow", code, false);

【讨论】:

  • 我应该在 html 部分放什么,因为代码需要正好在页面上的那个位置?怎么做?另外,在这种情况下,您使用“stackoverflow”做什么?谢谢
  • "stackoverflow" 只是脚本的唯一标识符,它可以是任何有效的 c# 字符串
  • 您从哪里获得 PageRepository 功能?我在代码中找不到该选项。谢谢
  • 对不起@Laziale我工作很忙,我会改变我的答案,它会更清楚。顺便说一下,PageRepository 只是一个我希望返回数字的模型类,它只是一个可以返回任何数字的示例。
猜你喜欢
  • 2011-07-03
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
相关资源
最近更新 更多