这是一个非常奇怪的错误。 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/