【问题标题】:Uncaught TypeError: Cannot set property 'onclick' of null onclick not working未捕获的类型错误:无法设置 null onclick 的属性“onclick”不起作用
【发布时间】:2013-04-19 19:52:52
【问题描述】:

下面是我的javascript,

<script type="text/javascript">
document.getElementById('auth').onclick=change;
function change(){
    this.className="account_holder";
}
</script>

html是

<td id="auth" class="authorised_reportericon" >
                        <a href="{% url incident.views.authorised_reporter %}">
                        <p align="center" style="color:black;font-size:16px;">Authorised Reporters</p></a>
                    </td>

我为 onclick 分配了 td 的 id,但它抛出错误为 Uncaught TypeError: Cannot set property 'onclick' of null

【问题讨论】:

  • 发生这种情况是因为 ID 为“auth”的元素不存在。为什么?因为 DOM 尚未完全加载以了解元素。使用window.onload = function() {} 并把你的逻辑放在那里

标签: javascript html


【解决方案1】:

document.getElementById('auth').onclick=change; 放在window.onload 内,例如:

window.onload = function () {
    document.getElementById('auth').onclick=change;
};

根据您收到的错误,我猜您的 Javascript 是在您的相关 HTML 呈现之前执行的,这意味着找不到带有 id“auth”的元素。将它放在整个 DOM 准备就绪的事件中应该可以解决问题。

演示:Here

【讨论】:

  • @mattytommo 谢谢你:)
  • 呵呵没问题,我在你发布答案时设置了它(只有他的代码),我添加了你的代码以确保,然后我想我会 +1 你并将链接添加为你是对的! :)
【解决方案2】:

很可能您已将脚本放置在文档的head 中,这意味着它在页面的其余部分呈现之前运行。

相反,将其移到body 内的最底部,就在结束&lt;/body&gt; 标记之前。

<!doctype html>
<html>
    <head>
        <title>my page</title>
    </head>
    <body>

        <!-- your page content -->

        <!-- your script -->
        <script type="text/javascript">
        document.getElementById('auth').onclick=change;
        function change(){
            this.className="account_holder";
        }
        </script>
    </body>
</html>

现在元素将在脚本运行之前可用。这是因为页面按从上到下的顺序呈现,而脚本在加载时会阻塞呈现。

因此,当脚本位于头部时,它会阻止其下方的其余页面呈现,直到脚本完成,这意味着 "auth" 尚不存在。

使用这种将脚本定位到最后的技术,它可能比等待window.onload 事件更快地运行。

【讨论】:

    猜你喜欢
    • 2018-01-03
    • 2014-02-07
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2020-02-02
    • 1970-01-01
    相关资源
    最近更新 更多