未捕获的类型错误:不能设置属性'onclick'null的onclick不起作用

Uncaught TypeError: Cannot set property 'onclick' of null onclick not working

本文关键字:onclick 不起作用 null 属性 不能 类型 错误 设置      更新时间:2023-09-26

见下面是我的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:不能设置属性'onclick'为null

document.getElementById('auth').onclick=change;放到window.onload中,如:

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

根据你得到的错误,我猜你的Javascript是在你的相关HTML被渲染之前执行的,这意味着没有找到id"auth"的元素。把它放在一个事件中,整个DOM都准备好了,应该可以解决这个问题。

这里演示:

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

相反,将它移动到body的最底部,就在结束的</body>标签之前。

<!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事件更快地运行。