未捕获的TypeError:链接不是HTMLButtonElement.onclick中的函数

编程入门 行业动态 更新时间:2024-10-27 20:29:45
本文介绍了未捕获的TypeError:链接不是HTMLButtonElement.onclick中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

This is a very strange error. HTML thinks the function is undefined, how do I solve this? Here's the code:

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

推荐答案

问题是 document.links 已经存在,对全局文档上的项的隐式引用优先于全局窗口上的隐式引用。也就是说,如果文档。< something> 存在且窗口。< something> 存在,如果您只是使用< something> 本身,解释程序将首先检查您使用的名称是否存在于文档在检查您使用的名称是否存在于窗口之前。 (您的链接 功能存在于 window.links )

The problem is that document.links already exists, and implicit references to items on the global document willl take precedence over implicit references on the global window. That is, if document.<something> exists and window.<something> exists, if you just use <something> by itself, the interpreter will first check to see if the name you're using exists on document before checking to see if the name you're using exists in window. (Your links function exists at window.links)

Document接口的链接只读属性返回文档中所有元素和元素的集合href属性的值。

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 而不是链接,默认为 document.links :

Either refer to window.links instead of just links, which will default to document.links:

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

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

Or, preferably, attach the handler properly using Javascript instead; inline handlers require pollution of the global scope and are generally considered to be pretty bad practice anyway:

document.querySelector('#links').addEventListener('click', () => { document.location = "links.html"; });

<button id="links">text content</button>

更多推荐

未捕获的TypeError:链接不是HTMLButtonElement.onclick中的函数

本文发布于:2023-11-23 03:39:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   链接   TypeError   onclick   HTMLButtonElement

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!