我正在尝试从文件隐藏代码中更改 JavaScript src。
<script type="text/javascript" runat="server" id="srcSurvey" language="JavaScript" src="mypage.asp?p=2"></script>
当我尝试从文件后面的代码中访问对象属性时,没有可用的 src 选项,我是否需要将 src 文件放在其他属性中?
我正在尝试从文件隐藏代码中更改 JavaScript src。
<script type="text/javascript" runat="server" id="srcSurvey" language="JavaScript" src="mypage.asp?p=2"></script>
当我尝试从文件后面的代码中访问对象属性时,没有可用的 src 选项,我是否需要将 src 文件放在其他属性中?
你不能访问这样的src
属性。HTML 属性可通过.Attributes
集合访问:
srcSurvey.Attributes["src"] = "my/directory/file.js";
在 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);