window.onload 中调用的函数无法识别元素
我在这里有点困惑。我认为window.onload
中指定的函数在页面加载之前没有执行。尽管如此,我在下面的代码中收到一个错误(这里是 jsfiddle 版本):
<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
:将图像移动到脚本上方一切都很好。
I am a bit confused here. I thought that the function specified in window.onload
did not execute before the page was loaded. Nervertheless, I get an error in the below code (heres the jsfiddle version):
<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" />
It gives me:
Error: document.getElementById("foo") is null
When moving the image above the script all works well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
window.onload
期望是一个函数 - 加载页面时它将调用该函数。但你分配给它的并不是一个函数。您指定立即执行
updateImage
函数,并且由于updateImage
正文中没有return
语句,因此返回值为未定义
。因此,最后,window.onload
的值为undefined
。解决方案是将这部分代码更改为:
这将导致它在加载窗口时调用该函数并执行您期望的操作。
window.onload
expects to be a function - which it will call when the page is loaded. But what you've assigned to it is not a function. You assignedwhich immediately executes the
updateImage
function, and since you don't have areturn
statement in the body ofupdateImage
, the return value isundefined
. Therefore, at the end,window.onload
has the valueundefined
.A solution would be to change that bit of code to:
This will cause it to call the function when the window has been loaded and do what you'd expect.
您可以使用触发器来检查元素是否已加载。
You can use trigger that will check is element loaded.
您的代码中有错误。
您没有为窗口加载分配函数处理程序。您正在分配 updateImage 函数的 RESULT。它在图像加载甚至添加到 DOM 之前立即执行。要分配函数处理程序,您需要:
或
或 使用 jQuery
You have an error in your code.
You are not assigning a function handler to the window onload. You are assigning the RESULT of the updateImage function. Which is executed immediately before image is loaded or even added to the DOM. To assign function handler you need:
or
or by using jQuery