以下是我的代码。
<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>
当我试图在(span add)中显示z的值时,我收到了以下错误。
TypeError: document.getElementById(...) is null
请帮帮我。
答案 0 :(得分:4)
更改顺序:将脚本放在元素后面,以便在调用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>
另一个解决方案是使用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>
答案 1 :(得分:3)
将代码添加到onload事件中,如下所示
window.onload = function () {
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("add").innerHTML = z;
}
演示:http://jsbin.com/luqeyo/1/edit?html,output
因为您在准备使用之前尝试调用文档。
更新:如果您不想等待,同时会加载所有资源(图片等),您可以使用此方法
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;
}