我在这里有点困惑。我认为指定的函数window.onload
在页面加载之前没有执行。尽管如此,我在下面的代码中遇到了错误(这是jsfiddle版本 http://jsfiddle.net/Claudius/raktx/):
<script>
function updateImage(url){
document.getElementById("foo").src = url;
}
window.onload = updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
</script>
<img id="foo" alt="" src="http://dummyimage.com/100x100/000/fff.png&text=bar" />
它给了我:
Error: document.getElementById("foo") is null
当将图像移动到脚本上方时一切正常。
window.onload
期望是一个函数 - 加载页面时将调用该函数。但你分配给它的并不是一个函数。你分配的
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
它立即执行updateImage
函数,并且因为你没有return
正文中的声明updateImage
,返回值为undefined
。因此,最后,window.onload
有价值undefined
.
解决方案是将这段代码更改为:
window.onload = function(){
updateImage("http://dummyimage.com/100x100/000/fff.png&text=qux");
}
这将导致它在窗口加载后调用该函数并执行您期望的操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)