简体   繁体   中英

How to programmatically insert a javascript into a web page?

I am using ASP.NET and C#. Essentially I want to build a string like this using C#:

string strScript = "<script type="text/javascript">stuff</script>";

Then I want to insert that as the very first javascript in the web page (note that it is important that it be the first script in the page).

Thanks in advance for the help!

EDIT: sorry for the newb question(s) ... I'm on a time crunch and my javascript/asp.net skills are practically null.

您可以将<asp:literal>放在页面顶部,然后将该文字的文本设置为服务器端页面加载时的javascript字符串。

我已经在以前的项目中成功使用了ClientScriptManager.RegisterClientScriptBlock方法。

protected void Page_Load(object sender, System.EventArgs e)
{
    myScript = "\n<script type=\"text/javascript\" language=\"Javascript\"   id=\"EventScriptBlock\">\n";
    myScript += "alert('hi');";
    myScript += "\n\n </script>";
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myKey", myScript, true);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM