简体   繁体   English

Asp.net RegisterStartupScript没有解雇

[英]Asp.net RegisterStartupScript not firing

In my asp.net application, I am trying to call a Javascript function, by doing the following: 在我的asp.net应用程序中,我试图调用Javascript函数,通过执行以下操作:

Page.ClientScript.RegisterStartupScript(this.GetType(), "goToDiv", "function goToDiv(){window.location.hash = '#ctl00_body_ApplicationFormContainer'};", true);        

But it is not firing. 但它并没有解雇。

The JavaScript function is being called after a postback event, but I think it should still fire, as I added the following code to my Page_Load : 在回发事件之后调用JavaScript函数,但我认为它仍然应该触发,因为我将以下代码添加到我的Page_Load

if (IsPostBack)
    {
        Response.Write("POSTBACK:" + DateTime.Now.ToString("hh.mm.ss.ffffff"));            
    }

and changed the startupscript to: 并将startupscript更改为:

Page.ClientScript.RegisterStartupScript(this.GetType(), "goToDiv", "alert('POSTBACK: "+DateTime.Now.ToString("hh.mm.ss.ffffff")+"')", true);         

and the JavaScript alert time was after the postback time, telling me the JavaScript alert is fired after the postback? 并且JavaScript警报时间是在回发时间之后,告诉我在回发后触发了JavaScript警报?

I then changed the code back and went to the sources tab in the console, before the startup script had been run, and entered: 然后我更改了代码并在运行启动脚本之前转到控制台中的sources选项卡,然后输入:

goToDiv()

which gave the following error: 出现以下错误:

Uncaught ReferenceError: goToDiv is not defined(…)

eg the function does not exist. 例如,该功能不存在。

I then entered it again, after the startup script event, and it ran, so I know the function is created - so why is it not running? 然后我再次进入它,在启动脚本事件之后,它运行了,所以我知道函数已经创建 - 所以为什么它没有运行?

My code seems to be syntactically correct, so I cannot see what the problem is? 我的代码似乎在语法上是正确的,所以我看不出问题是什么?

Your code:- 你的代码: -

Page.ClientScript.RegisterStartupScript(this.GetType(), "goToDiv",
   "function goToDiv(){window.location.hash = '#ctl00_body_ApplicationFormContainer'};",
    true);

is simply adding a Javascript function but not executing it. 只是添加一个Javascript函数,但不执行它。 You need to trigger this function right? 你需要触发这个功能吗?

Simply add a button to test:- 只需添加一个按钮即可测试: -

<input type="button" onclick="goToDiv()"  value="Foo" />

When you click this button it will execute this Javascript function. 当您单击此按钮时,它将执行此Javascript函数。

If your intention is to execute some piece of block then why you are creating a function? 如果你打算执行一些块,那你为什么要创建一个函数? You can execute the Javascript statements itself. 您可以自己执行Javascript语句。

and the JavaScript alert time was after the postback time, telling me the JavaScript alert is fired after the postback? 并且JavaScript警报时间是在回发时间之后,告诉我在回发后触发了JavaScript警报?

Yes obviously, you are registering the Javascript code at server side so when the page is rendered in the browser(client) only then your JS code will be executed. 是的,很明显,您正在服务器端注册Javascript代码,因此当页面在浏览器(客户端)中呈现时,您的JS代码将被执行。

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

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