<html>
<div id="div"></div>
<script>
function test(){
   var div = document.getElementById('div');
   div.innerHTML += 'a';//此处报错
}
test();
</script>
</html>
div.innerHTML += 'a';运行到这句就会报错,错误信息是:div is null
但如果我把<div id="div"></div>标签中加一些内容就不会报错了,为什么?

解决方案 »

  1.   

    你敢把div写在<body>里面不?
      

  2.   

    body标签都木有。。
    <html>
    <body>
    <div id="div"></div>
    <script>
    function test(){
      var div = document.getElementById('div');
      div.innerHTML += 'a';//此处报错
    }
    test();
    </script>
    </body>
    </html>
      

  3.   

    为什么没有<body>就不行呢?
      

  4.   

    因为不在标准的文档树里面
    要不你丢到<head>里面document也可以找到,但浏览器会解析成什么样我就不知道了
      

  5.   

    HTMl基本格式<html>
    <head>
    </head>
    <body>
    </body>
    </html>