javascript中document.getelementbyid缺少对象的问题原因

下面这段代码浏览器端运行时会报错:缺少对象
原因是:在还未加载img对象前就试图通过它的id得到img对象。
  从这个错误就可以看出Javascript和html的一些特性。
  下面是报错的代码段
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<link rel="stylesheet" type="text/css" href="mario.css" /> 
<head>
   <script language="javascript"> 
      
			var mymario=document.getElementById('mymario'); 
			window.alert(mymario.style.top);
		
          
        </script>  
</head>
<body>
 <div class="gamediv">  
            <img id="mymario" src="i2.png" style="left:100px; top:50px; position:absolute;" /> <!--用到了绝对定位-->  
        </div> 
		
</body>
</html>



修改后

下面这段代码不会报错。原因:加载完img之后再通过它的id得到img对象

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html>
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<link rel="stylesheet" type="text/css" href="mario.css" /> 
<head>
   <script language="javascript"> 
        function show(){
			var mymario=document.getElementById('mymario'); 
			window.alert(mymario.style.top);
		}
          
        </script>  
</head>
<body>
 <div class="gamediv">  
            <img id="mymario" src="i2.png" style="left:100px; top:50px; position:absolute;" /> <!--用到了绝对定位-->  
        </div> 
		
</body>
</html>
注:源代码片段来自传智播客韩老师的课堂代码。错误为本人遇到。觉得很有价值,和大家分享

猜你喜欢

转载自blog.csdn.net/w15454/article/details/25471437