为什么document.getElementById返回null值?

dub*_*ber 1 javascript html5 web-applications canvas html5-canvas

我调试了我的代码并意识到我的Javascript中的方法无法正常工作.任何人都知道为什么?

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tetris</title>
<link rel="stylesheet" href="css/app.css">
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<canvas id="tetrisBoard" width="800" height="600">
  Your browser does not support HTML 5.
</canvas>
<p>
</p>
</body>
</html>   
Run Code Online (Sandbox Code Playgroud)

main.js:

board = document.getElementById("tetrisBoard")                                                                                                                                                              
ctx = board.getContext("2d")
ctx.fillStyle = "rgb(200, 0, 0)"
ctx.fillRect 10, 10, 55, 50
Run Code Online (Sandbox Code Playgroud)

结果document.getElementById("tetrisBoard")是null值.为什么?

j08*_*691 5

因为您在元素存在之前调用代码.将脚本放在关闭正文标记之前,你会没事的.