javascript - 未捕获的类型错误 : links is not a function at HTMLButtonElement. onclick

标签 javascript html error-handling

这是一个非常奇怪的错误。 HTML 认为该函数未定义,我该如何解决?这是代码:

<button id="links" onclick="links()">Links</button>
    <script>function links(){document.location = ("links.html")}</script>

最佳答案

问题是 document.links 已经存在,并且隐式引用了全局 document 上的项目将优先于全局 window 上的隐式引用.也就是说,如果 document.<something>存在并且window.<something>存在,如果你只使用 <something>解释器本身将首先检查您使用的名称是否存在于 document 上在检查您使用的名称是否存在于 window 之前. (您的 links 函数 存在于 window.links )

The links read-only property of the Document interface returns a collection of all elements and elements in a document with a value for the href attribute.

<button id="links" onclick="console.log(links === document.links); links();">text content</button>
<script>
function links() {
  document.location = ("links.html")
}
</script>

要么引用window.links而不仅仅是 links ,默认为 document.links :

<button id="links" onclick="window.links();">text content</button>
<script>
function links() {
  document.location = ("links.html")
}
</script>

或者,最好使用 Javascript 正确附加处理程序;内联处理程序需要全局范围的污染,并且通常被认为是非常糟糕的做法:

document.querySelector('#links').addEventListener('click', () => {
  document.location = "links.html";
});
<button id="links">text content</button>

关于javascript - 未捕获的类型错误 : links is not a function at HTMLButtonElement. onclick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52796597/

相关文章:

javascript - 在页面加载时设置具有不同值和标签的列表框值

javascript - 如何在javascript之前加载图像

java - JUnit @Rule ExpectedException

php - API 响应 - 从包含的类中收集错误

javascript - 使用 Iscroll 重置自动滚动间隔

javascript - 在没有对象包装器的情况下使用 Jquery $.grep 过滤对象数组

javascript - 如何在服务器端(nodejs)生成部分html代码?

javascript - 使用我自己的 javascript 功能包装第 3 方 Web 应用程序

javascript - 谷歌地图标记上的标签上未显示文本

r - 如何使循环跳过产生警告的输入?