未捕获的TypeError:lang不是函数 [英] Uncaught TypeError: lang is not a function

查看:125
本文介绍了未捕获的TypeError:lang不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆