简体   繁体   English

在C#中回发运行javascript

[英]Run a javascript on postback in c#

I used the below manner to run a JavaScript upon postback and it worked fine for me. 我使用以下方式在回发时运行JavaScript,它对我来说很好用。

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'hidden';</script>");
        Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>function show()</script>");
    }
    else
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>document.getElementById('apDiv1').style.visibility = 'visible';</script>");
    }
}

The above code worked fine and now I want to try something like below. 上面的代码工作正常,现在我想尝试以下类似的方法。

protected void Page_Load(object sender, EventArgs e)
{
    if (this.IsPostBack)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),"verify","<script type='text/javascript'>verify1();</script>");
    }
    else
    {
    }
}

in the above code verify1() is a JavaScript linked externally to ASPX page. 上面的代码中的verify1()是从外部链接到ASPX页面的JavaScript。 I am unable to execute verify1() function using this code. 我无法使用此代码执行verify1()函数。 And verify1() function works fine when placed as <body onload="verify1();"> Is there any syntax error(s) in my above code? 并且当放置为<body onload="verify1();">时, verify1()函数工作正常,我的上述代码中是否有语法错误?

this may help you, 这可以帮助您,

Page.ClientScript.RegisterStartupScript(this.GetType(), "verify", "verify1()", true); Page.ClientScript.RegisterStartupScript(this.GetType(),“ verify”,“ verify1()”,true);

Maybe that script is being executed before verify1()'s function definition. 也许该脚本是在verify1()函数定义之前执行的。 By the time body.onload fires, the main page has completed parsing and all external scripts have been loaded, which is why it works in that scenario. 在body.onload触发时,主页已完成解析并且所有外部脚本均已加载,这就是它在这种情况下起作用的原因。

Can you use jquery? 你可以使用jQuery吗? One option is to use jQuery's onload functionality, which won't be executed until everything is intialized: 一种选择是使用jQuery的onload功能,直到所有内容初始化后才会执行:

$( function() { ...my startup code... });

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

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