javascript中onload()的调用时间问题
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片反转</title>
</head>
<body>
<a href="next1.htm" ><img src="images/mouse_one_off.jpg" id="one"/></a> <br/>
<a href="next2.htm" ><img src="images/mouse_two_off.jpg" id="two"/></a>
<script type="text/javascript">
window.onload = rolloverInit();
function rolloverInit() {
for(var i=0 ; i < document.images.length; i++) {
if(document.images[i].parentNode.tagName == "A") {
setUpRollover(document.images[i]);
}
}
}
function setUpRollover(thisImage) {
thisImage.outImage = new Image();
thisImage.outImage.src = thisImage.src;
thisImage.onmouseout = function() {
this.src = this.outImage.src;
}
thisImage.overImage = new Image();
thisImage.overImage.src = "images/mouse_" + thisImage.id + "_on.jpg";
thisImage.onmouseover = function() {
this.src = this.overImage.src;
}
}
</script>
</body>
</html>
刚学js没多久
onload应该是在页面加载完毕的时候才执行的
上面的运行的时候js 中的 for()循环中 document.images.length 这条语句测试是 为2 的
即为两个 img 标签 是正确的
但是我把 js 代码放在 head标签中的时候 运行测试alert 的时候 怎么 document.images.length 为0 了
按理 应该onload 运行的时候 页面已经加载完成 此时的时候 document.images.length 应该为 2 的
书上的代码 案例 是 放在 head 里面的
为什么 当我 这样 就不对? 浏览器 chrome
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片反转</title>
<script type="text/javascript">
window.onload = rolloverInit();
function rolloverInit() {
for(var i=0 ; i < document.images.length; i++) {
if(document.images[i].parentNode.tagName == "A") {
setUpRollover(document.images[i]);
}
}
}
function setUpRollover(thisImage) {
thisImage.outImage = new Image();
thisImage.outImage.src = thisImage.src;
thisImage.onmouseout = function() {
this.src = this.outImage.src;
}
thisImage.overImage = new Image();
thisImage.overImage.src = "images/mouse_" + thisImage.id + "_on.jpg";
thisImage.onmouseover = function() {
this.src = this.overImage.src;
}
}
</script>
</head>
<body>
<a href="next1.htm" ><img src="images/mouse_one_off.jpg" id="one"/></a> <br/>
<a href="next2.htm" ><img src="images/mouse_two_off.jpg" id="two"/></a>
</body>
</html>
谢谢! javascript
[解决办法]
window.onload?=?rolloverInit();
把括号去掉试试
待括号的,是直接就执行了,你这样写,是把rolloverInit()的返回值赋值给了onload
不是绑定onload的执行函数,去掉括号,才是绑定函数呢。
window.onload?=?rolloverInit;
换成这样