js有关问题:document.getElementById 为null的解决方案

js问题:document.getElementById 为null的解决方案

在IE8下运行如下代码,出现document.getElementById缺少对象的问题。

<html>
 <head>
  <title> Javascript问题测试</title>  
  <script language="javascript">  		
		function test(){
			alert(document.getElementById("b"));
		}
		test();
  </script>
 </head>
 <body>
	<div id="a">
		<span id="b">测试</span>
	</div>	
 </body>
</html>

 

运行结果如图: 

js有关问题:document.getElementById 为null的解决方案

 

解决方案:把JS代码放在要获取的元素的后面

<html>
 <head>
  <title> Javascript问题测试</title>  
  
 </head>
 <body>
	<div id="a">
		<span id="b">测试</span>
	</div>
	<script language="javascript">  		
		function test(){
			alert(document.getElementById("b"));
		}
		test();
	</script>
 </body>
</html>

 

总结:出现问题的原因是 HTML 从上至下 解析 , 应该先 有"对象" ,再去"引用".