在asp.net c#中运行时添加多个js文件

时间:2014-02-18 06:37:52

标签: javascript php html asp.net css

我希望在按钮单击时在运行时在我的ASP.NET c#页面中添加多个.js文件。

Literal link2 = new Literal();
Literal link3 = new Literal();
Literal link4 = new Literal();

link2.Text = "<script src=\"Theme1/js/jquery-1.8.2.min.js\" type=\"text/javascript\" />";
link3.Text = "<script src=\"Theme1/js/supersized.3.2.7.min.js\" type=\"text/javascript\" />";
link4.Text = "<script src=\"Theme1/js/supersized-init.js\" type=\"text/javascript\" />";

base.Page.Header.Controls.Add(link2);
base.Page.Header.Controls.Add(link3);
base.Page.Header.Controls.Add(link4);

2 个答案:

答案 0 :(得分:0)

更好的方法是使用RegisterStartupScript方法:

http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx

示例:

string jsBlock = "<script src='myJsFile.js'></script>";
if (!Page.ClientScript.IsStartupScriptRegistered("myJsInclude"))
   Page.ClientScript.RegisterStartupScript(typeof(string), "myJsInclude", jsBlock, false);

OR

在你的情况下更好的RegisterClientScriptInclude:

http://msdn.microsoft.com/en-us/library/kx145dw2.aspx

示例

if (!Page.ClientScript.IsClientScriptIncludeRegistered("myJsInclude"))
   Page.ClientScript.RegisterClientScriptInclude("myJsInclude", "myJsFile.js");

答案 1 :(得分:0)

            HtmlLink css3 = new HtmlLink();
            css3.Href = "theme2/css/style.css";
            css3.Attributes["rel"] = "stylesheet";
            css3.Attributes["type"] = "text/css";
            css3.Attributes["media"] = "all";
            Page.Header.Controls.Add(css3);