在我的HTML中,我在脚本标记中定义 lang 函数并添加Test Fire!点击时必须调用 lang 的按钮:
In my HTML I define the lang function in the script tag and add the "Test Fire!" button which has to call lang on click:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Testing Functions</title> <script type="text/javascript"> function lang() { alert("Hello, World! It's JavaScript this time"); } </script> </head> <body> <form action=""> <input type="button" value="Test Fire!" onclick="lang();"> </form> </body> </html>
但是,如果我单击按钮我会收到此错误:
However, if I click the button I get this error:
未捕获TypeError: lang 不是函数
但如果我从 lang 对于其他任何代码都可以正常工作。
But if I change the function name from lang to anything else this code works fine.
推荐答案考虑以下代码:
<input type="button" value="Test Fire!" onclick="debugger;" />
当你打开调试器时,你会看到似乎有一个隐含的带范围的 onclick ,使所有的< ;输入> 的属性无需参考按钮即可访问。
When you open your debugger, you’ll see that there seems to be an implicit with scope wrapped around the onclick, making all the <input>’s properties accessible without needing to refer to the button.
这意味着所有全局属性( lang 就是其中之一),其他几个特定于按钮的覆盖被覆盖。例如。 value , type 也不起作用。
This means that all global attributes (lang is one of them) and several others specific to buttons are overridden. E.g. value, type also wouldn’t work.
您最好的选择是使用添加事件侦听器的标准方法: addEventListener 。
Your best bet is to use the standard way of adding event listeners: addEventListener.
<input type="button" value="Test Fire!" /> <script> function lang() { alert("Hello, World! It's JavaScript this time"); } document.querySelector("input").addEventListener("click", lang); </script>
更多推荐
未捕获的TypeError:lang不是函数
发布评论