Javascript javascript未捕获的引用错误onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26071019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:17:53  来源:igfitidea点击:

javascript uncaught reference error onclick

javascripthtmlfunctionbuttononclick

提问by Mr.Clefable

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.

试图用一个按钮调用一个 javascript 函数,而该按钮在点击时没有做任何事情。调试器返回“未捕获的引用错误:printNumber 未定义。

printNumberis the function I want to call.

printNumber是我想调用的函数。

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:

这是我的 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.

任何人都可以向我指出问题的出处吗?谢谢,这是一个编程课,我希望其他可能也遇到过这个的人能看到这个。

回答by teynon

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

使用<script type="text/javascript">并注意您不能x以您想要的方式递增。您正在增加一个局部变量,而不是全局变量。

    <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>