Cant call Javascript function from button onclick

2020-08-16 05:57发布

问题:

when ever i call a JavaScript function from asp:button onclick event i got this error message

HTML

<asp:Button ID="btnFromCalOpen" runat="server" Text=" &gt; "  onclick="ShowCal()"  CssClass = "SElementHide" />

Javascript

function ShowCal() {

    var elem = document.getElementById('MainContent_CalendarFrom');
    if (elem.visibility = "hidden" )
    {
    elema.style.visibility = "visible";
    elema.style.display = "block";
    }
    else
    {
    elema.style.visibility = "hidden";
    elema.style.display = "none";
    }
}

Error Compiler Error Message: BC30456: 'ShowCal' is not a member of 'ASP.default_aspx'.

Please Help

回答1:

Use OnClientClick to have your ASP.NET button run a JavaScript method before calling its server-side method. OnClick specifies the server side method to run.

<asp:Button ID="btnFromCalOpen" runat="server" 
         Text=" &gt; "  CssClass = "SElementHide" 
         OnClientClick="ShowCal()" />


回答2:

use OnClientClick. onclick is for a server side handler.

also you need to check elem.style.visibility.

also you're creating elem in your js function and then trying to access elema.



回答3:

Have you tried the OnClientClick property?

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx

Also, this does not look correct:

if (elem.visibility = "hidden")

Should be closer to:

if (elem.style.visibility == "hidden")

Are you also looking for the button to prevent post back? Then, return false in your ShowCal javascript function.