繁体   English   中英

onclick 说函数没有定义,而它是

[英]onclick says function is not defined while it is

尝试使用按钮内的“onclick”事件执行函数时,我在控制台中收到此错误。 我得到的错误是,

Uncaught ReferenceError: foo is not defined
    onclick http://localhost:3001/bar:1
    onclick http://localhost:3001/bar:1

我在<body>标签中像这样定义了foo ,后跟一个script标签,

function foo(){
    fooBar();
}

谢谢。

编辑:这是我的代码。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="app lol">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <title><% title %></title>
</head>
<body>
    <script>
        function foo() {
            fooBar();
        }
    </script>
    <button onclick="foo()">bar</button>
</body>
</html>

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="app lol"> <script src="unpkg.com/axios/dist/axios.min.js"> </script> <title></title> </head> <body> <script> function fooBar() { alert("hey"); } function foo() { fooBar(); } </script> <button onclick="foo()">bar</button> </body> </html>

 <html> <head><title></title></head> <body> <button id="btn" onClick="foo()">Click me </button> <script> btn = document.getElementById("btn"); function foo(){ btn.style.color = "red"; } </script> </body> </html>

这有效!

<html>
<head><title></title></head>
<body>
<button id="btn" onClick="foo()">Click me </button>
<script>
btn = document.getElementById("btn");
function foo(){
alert("heya");
}
</script>
</body>
</html>

这是您的设置的样子吗? 如果是,应该没有任何错误。

<script>
  function foo () {
    console.log('Foo function');
  }
</script>

<button onclick="foo()"> My Button </button>

为您的按钮添加一个 ID。 onclick有点问题,因为谷歌安全功能阻止你这样做。 将 JavaScript 和 HTML 分开甚至是一个好主意。

我通常给一个 div 分配一个 ID,然后querySelector它们。

<div id="an-id">
  <input />
</div>
document.querySelector("#an-id").querySelector("input").addEventListener("click", foo);

(将您的脚本放在按钮后面)

首先,我想请您辞去开发人员的工作。 你是所有开发人员的耻辱。

现在至于答案,将您的函数声明放在“window.onload = ()=>{}”中。

谢谢,请辞掉你的工作,去当看门人什么的。

艾普罗

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM