简体   繁体   中英

javascript uncaught reference error onclick

Trying to call a javascript function with a button, and the button is not doing anything on click. The debugger returns "uncaught reference error: printNumber is not defined.

printNumber is the function I want to call.

I did a search and most people with this problem did not use the proper syntax for declaring their function, defined their function within another function (function out of scope), or put their functions after they are called. It turns out nothing in my head is running. I tried to put a prompt in it for example, and the prompt did not show up.

Here is my script:

    <head>
    <script type="javascript">
    var x=0;
    function addNumber(x){
        x = x + 1;
        return x;   
    }

    function printNumber(number){
        document.getElementById("number").innerHTML=addNumber(number);
    }

    </script>
    </head>

Here is my HTML:

    <body>
<p><center><b>The number of times the button has been clicked is ... <b><p>
<br>
<div id="number"></div>
<br>
<form>
    <input type="button" id="StartButton" value="Click to add 1 to counter" onClick="printNumber(x)">
</form>
</center>

Can anybody point out to me where the problem is coming from? Thank you, this is for a programming class, and I hope that others who might also encounter this will see this.

Use <script type="text/javascript"> and note that you can't increment x in the way you wanted. You are incrementing a local variable, not the global one.

  <html> <head> <script type="text/javascript"> var x=0; function addNumber(){ x = x + 1; return x; } function printNumber(number){ document.getElementById("number").innerHTML=addNumber(); } </script> </head> <body> <p><center><b>The number of times the button has been clicked is ... <b><p> <br> <div id="number"></div> <br> <form> <input type="button" id="StartButton" value="Click to add 1 to counter" onClick="printNumber()"> </form> </center> </body> </html> 

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