【问题标题】:Uncaught TypeError: links is not a function at HTMLButtonElement.onclick未捕获的类型错误:链接不是 HTMLButtonElement.onclick 处的函数
【发布时间】:2019-03-18 16:37:33
【问题描述】:

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

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

【问题讨论】:

    标签: javascript html error-handling


    【解决方案1】:

    问题是document.links 已经存在,并且对全局document 上的项目的隐式引用将优先于全局window 上的隐式引用。也就是说,如果document.&lt;something&gt; 存在且window.&lt;something&gt; 存在,如果您只使用&lt;something&gt;,解释器将首先检查您使用的名称是否存在于document 上,然后再检查名称是否存在您使用的存在于window。 (您的links 函数 存在于window.links

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

    <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";
    });
    &lt;button id="links"&gt;text content&lt;/button&gt;

    【讨论】:

    • 哦,谢谢,可以,但是整页中的按钮样式仍然无法正确显示
    • 您没有在问题中发布任何 CSS - 听起来像是一个完全独立的问题。
    【解决方案2】:

    那是因为您正在立即调用您的函数。尝试以这种方式更改您的代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 2019-05-24
      • 2021-12-15
      • 2019-10-26
      相关资源
      最近更新 更多