javascript getElementById 和 null - 为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8864776/
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
getElementById and null - why?
提问by lunar
Why doesn't this code work? I'am using FF.
为什么这段代码不起作用?我正在使用FF。
<head>
<script type="text/javascript">
document.getElementById("someID").onclick = function(){
alert("Yahooo");
}
</script>
</head>
<body>
<a href="#" id="someID">someID</a>
</body>
</html>
I'm getting javascript error getElementById equals to null.
我收到 javascript 错误 getElementById 等于 null。
回答by TimWolla
The needed DOM is not loaded when the script is executed. Either move it down (below the href) or define it like this:
执行脚本时未加载所需的 DOM。将其向下移动(在 href 下方)或如下定义:
window.onload = function () {
document.getElementById("someID").onclick = function(){
alert("Yahooo");
}
}
window.onload will be called when the page is completely loaded.
window.onload 将在页面完全加载时调用。
回答by ziesemer
Because the element doesn't yet exist when the script runs - the document hasn't been rendered yet. Either run the script in a script block after the related HTML, or use a "document on ready" event handler - preferably from something like jQuery's .ready()
event, or the native window.onload
.
因为脚本运行时该元素还不存在 - 文档尚未呈现。要么在相关 HTML 之后的脚本块中运行脚本,要么使用“文档就绪”事件处理程序 - 最好来自 jQuery.ready()
事件或本机window.onload
.