未捕获的TypeError:链接不是HTMLButtonElement.onclick中的函数 [英] Uncaught TypeError: links is not a function at 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中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!