Html 未捕获的类型错误:无法设置 null onclick 的属性“onclick”不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16222895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot set property 'onclick' of null onclick not working
提问by user2086641
see below is my javascript,
见下面是我的javascript,
<script type="text/javascript">
document.getElementById('auth').onclick=change;
function change(){
this.className="account_holder";
}
</script>
html is
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>
I assigned td's id for onclick,but it is trowing error as Uncaught TypeError: Cannot set property 'onclick' of null
我为 onclick 分配了 td 的 id,但由于 Uncaught TypeError: Cannot set property 'onclick' of null 导致错误
回答by Ian
Put document.getElementById('auth').onclick=change;
inside of window.onload
, like:
放在document.getElementById('auth').onclick=change;
里面window.onload
,比如:
window.onload = function () {
document.getElementById('auth').onclick=change;
};
According to the error you're getting, I'm guessing your Javascript is executed before your relevant HTML is rendered, meaning the element with the id
"auth" isn't found. Putting it in an event where the whole DOM is ready should fix the problem.
根据您收到的错误,我猜您的 Javascript 是在呈现相关 HTML 之前执行的,这意味着id
未找到带有“auth”的元素。将它放在整个 DOM 准备就绪的事件中应该可以解决问题。
Demo: Here
演示:这里
回答by yowza
Most likely you've placed the script in the head
of the document, which means it's running before the rest of the page has been rendered.
很可能您已经将脚本放在head
文档的 的 中,这意味着它在页面的其余部分呈现之前正在运行。
Instead, move it inside the body
, to the very bottom, just before the closing </body>
tag.
相反,将它移动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>
Now the elements will be available before the script runs. This is because the page renders in order from top to bottom, and scripts block the rendering when loading.
现在这些元素将在脚本运行之前可用。这是因为页面是按照从上到下的顺序渲染的,加载的时候脚本会阻塞渲染。
So when the script is in the head, it prevents the rest of the page below it from rendering until the script is complete, which means the "auth"
doesn't yet exist.
因此,当脚本位于头部时,它会阻止其下方的页面的其余部分呈现,直到脚本完成,这意味着"auth"
尚不存在。
Using this positioning technique of the script toward the end allows it to run potentially much sooner than waiting for a window.onload
event.
在最后使用脚本的这种定位技术可以让它比等待window.onload
事件更快地运行。