javascript - 在 body 标签内声明函数会导致 "Function not defined"

标签 javascript html function onclick

我在 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未定义”。我做错了什么?

最佳答案

以下似乎工作得很好:

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

如果您收到该错误,则可能是来自您提供的代码之外的其他地方。

关于javascript - 在 body 标签内声明函数会导致 "Function not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15885597/

相关文章:

javascript - 从数据库中存储的字符串创建 html5 页面

javascript - 无论如何都会出现具有 "display: none"样式的 Div

php - 一起使用 HTML 和 Php?

javascript - 提交 html 选择作为多维数组,如复选框

php:在 "echo"内部执行数学运算。还将变量名传递给函数

函数的代码解释

javascript - 绘制 HTML5 Canvas 脉冲线

jquery - jquery中如何使用焦点?

python - 从 python 中的函数对象获取易于阅读的函数名称

javascript - 如何设置li :before with ng-style的css