简体   繁体   中英

Run a javascript on postback in c#

I used the below manner to run a JavaScript upon postback and it worked fine for me.

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. I am unable to execute verify1() function using this code. And verify1() function works fine when placed as <body onload="verify1();"> Is there any syntax error(s) in my above code?

this may help you,

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

Maybe that script is being executed before verify1()'s function definition. 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.

Can you use jquery? One option is to use jQuery's onload functionality, which won't be executed until everything is intialized:

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

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