在body标签内声明函数会导致“函数未定义”

Declare function inside the body tag leads to "Function not defined"

本文关键字:函数 未定义 函数未定义 body 标签 声明      更新时间:2023-09-26

我在html的body标签中呈现了一个java脚本函数。在java脚本之后有一个按钮,该按钮调用该函数,该函数由onclick属性声明。

<script type="text/javascript">
    function f(caller){
        console.log('test');
    }
</script>
<button onclick="f(this)" type="button">A button</button>

问题是它说"ReferenceError: f is not defined"。我做错了什么?

下面的代码似乎可以正常工作:

<!DOCTYPE html>
<html>
<head>
    <title>Demo</title>
    <script type="text/javascript">
        function f(caller){
            console.log('test');
        }
    </script>
<body>
    <button onclick="f(this)" type="button">A button</button>
</body>
</html>

如果你收到这个错误,它可能是来自其他地方,而不是你提供的代码。

而不是在body标记中找到脚本的正确位置,我建议使用窗口。onload,功能以及使用addEventListener()head标签内的script标签内绑定事件,它应该是甚至在外部.js文件中。

给你的按钮一个id,如果你想使用getElementById()来选择它,类似于:

window.onload = function () {
    var f = function(caller) {
        console.log('test');
    };
    var myButton = document.getElementById('myButton');
    myButton.addEventListener('click', function(){
        f(this);
    });
};

——使用window.onload()addEventListener()


我的问题是我写了

<script type="text/javascript" src="........." />
<script type="text/javascript">
    function f(caller){
        console.log('test');
    }
</script>

但是它应该有一个</script>标签。

<script type="text/javascript" src="........." ></script>
<script type="text/javascript">
    function f(caller){
        console.log('test');
    }
</script>