简体   繁体   English

动态将js添加到asp.net文件

[英]Dynamically adding js to asp.net file

In my Page_Load I identify the page header block from my master page and add javascript from an XML file to that part of the page. 在我的Page_Load中,我从母版页中标识页面标题块,然后将XML文件中的javascript添加到页面的该部分。

It doesn't seem to be loading in time. 它似乎没有及时加载。 If I explicitly put the script reference on the page, it works. 如果我将脚本引用明确放在页面上,那么它将起作用。 But not when I load through the page_load event. 但是当我通过page_load事件加载时却没有。

Should it be loaded sooner? 是否应该尽快加载?

You're not adding any code so I'm not able to tell you what you're doing wrong. 您没有添加任何代码,所以我无法告诉您您在做什么错。 Instead, I'll tell you a valid way to add script references from code behind. 相反,我将告诉您一种从后面的代码添加脚本引用的有效方法。

Something like this on Page_Load should do the trick Page_Load上的类似内容应该可以解决问题

var js = new HtmlGenericControl("script");
js.Attributes["type"] = "text/javascript";
js.Attributes["src"] = "myFile.js";
Page.Header.Controls.Add(js);

您无法在您的页面中输入以下方法,

protected void OnInit(EventArgs e)

Use this here i have js folder on root and it work fine for me. 在这里使用它,我在根目录上有js文件夹,对我来说很好用。

function addJavascript(jsname, pos) {
            var th = document.getElementsByTagName(pos)[0];
            var s = document.createElement('script');
            s.setAttribute('type', 'text/javascript');
            s.setAttribute('src', jsname);
            th.appendChild(s);

        }

 addJavascript('js/table.js', 'Head');

call addJavascript method with file path and parent tag where you want to add javascript file 使用要添加JavaScript文件的文件路径和父标记调用addJavascript方法

Hope it works for you.. 希望这对你有用..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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