|
阅读:8253回复:0
onload与页面加载顺序问题<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
<head>
<title>新建网页</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<script type="text/javascript">
var obj = document.getElementById("testInfo");//有一个id为testInfo的A元素在页面
window.onload=function(){
obj.onclick=function(){
alert(this.value);
}
}
//这样写就会报错,第10行会obj为空或不是对象
//但是这样写就不会报错:
// window.onload=function(){
// var obj = document.getElementById("testInfo");//有一个id为testInfo的A元素在页面
// obj.onclick=function(){
// starOperate();
// overOperate();
// }
// }
//希望有高手可以帮忙解释下原理。谢谢
</script>
</head>
<body>
<input type="text" value="123" id="testInfo" />
</body>
</html>
关于上面的问题,其实就是网页加载顺序与onload事件触发的时间, 首先:了解下onload的事件触发:onload是在整个页面 (DOM) 加载完毕后触发。 然后是:网页加载及网页中的<script>标签。它是按照在页面上的顺序来加载。从上向下一句句解析。 var obj = document.getElementById("testInfo");//有一个id为testInfo的A元素在页面
window.onload=function(){
obj.onclick=function(){
alert(this.value);
}
}
上面的代码会出现错误。obj为空。原因很简单。 var obj = document.getElementById("testInfo");上面这句代码,没有在onload中,所以,它是根据网页顺序来加载的。根据上面的网页,可以发现:它是在定义此ID元素前面的。所以,它所提示:obj为null;
<input type="text" value="123" id="testInfo" />这样的写法其实是没有错的。想不报错,很简单。把<script>标签放到<body>标签之后,来执行,上面的代码就完全没有问题了(注:为上述的顺序问题,一般将<script>标签放到</body>标签之前) window.onload=function(){
var obj = document.getElementById("testInfo");
obj.onclick=function(){
alert(this.value);
}
}这里也可以,不会报错。因为都放在Onload里,在执行里,整个网页(DOM)已经加载完了 |
|
|