JavaScript :TypeError: document.getElementById(...) 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27562252/
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
JavaScript :TypeError: document.getElementById(...) is null
提问by Saurabh Shrikhande
Following is my code.
以下是我的代码。
<html>
<head>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("add").innerHTML = z;
</script>
</head>
<body>
<h1>Demo</h1>
<div id="demo">Addition of 5 and 6 is <span id="add"></span>
</div>
</body>
</html>
And when I am trying to display the value of z in (span add) I am getting following error.
当我尝试在 (span add) 中显示 z 的值时,出现以下错误。
TypeError: document.getElementById(...) is null
Please help me.
请帮我。
回答by Denys Séguret
Change the order : put the script after the element so that it's defined when getElementById
is called.
更改顺序:将脚本放在元素之后,以便在getElementById
调用时定义它。
<body>
<h1>Demo</h1>
<div id="demo">Addition of 5 and 6 is <span id="add"></span>
</div>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("add").innerHTML = z;
</script>
</body>
Another solution would be to use jQuery's ready
function :
另一种解决方案是使用 jQuery 的ready
函数:
<script>
$(function(){
var x = 5;
var y = 6;
var z = x + y;
$('#add').html(z); // if you use jQuery, you may as well do that
});
</script>
</head>
<body>
<h1>Demo</h1>
<div id="demo">Addition of 5 and 6 is <span id="add"></span>
</div>
</body>
回答by Alexander T.
Add your code to onload event like this
将您的代码添加到这样的 onload 事件
window.onload = function () {
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("add").innerHTML = z;
}
Demo: http://jsbin.com/luqeyo/1/edit?html,output
演示:http: //jsbin.com/luqeyo/1/edit?html,output
Because you try call document before it ready to use.
因为你在它准备好使用之前尝试调用文档。
Update:if you don't want wait, while will load all resources (images etc.) you can use this approach
更新:如果您不想等待,while 将加载所有资源(图像等),您可以使用此方法
document.onreadystatechange = function () {
if (document.readyState === "complete") {
ready();
}
}
function ready() {
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("add").innerHTML = z;
}