jQuery:如何检查数组中的所有图像何时加载?
我有一个图像数组(图像的确切数量各不相同),当它们全部加载时,我想要执行一些代码。
我尝试过,但它不起作用:
myImgArray.load(function(){
alert('loaded');
});
我明白了
33:未捕获类型错误:对象 [object Object]、[object Object]、[object Object]、[object Object] 没有方法“load”
我不认为for循环或类似的东西会起作用,因为图像可能,并且可能会以“随机”顺序加载。
I have an array of images (the exact number of images varies), and when they all load I want some code to execute.
I tried this but it doesn't work:
myImgArray.load(function(){
alert('loaded');
});
I get
33: Uncaught TypeError: Object [object Object],[object Object],[object Object],[object Object] has no method 'load'
I don't think a for loop or something similar would work because the images might, and probably will, load in 'random' order.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道的唯一方法是为每个图像附加一个加载处理程序,并记录已加载的图像数量。当您达到总数时,它们就全部加载完毕。
下面是执行此操作的代码:
您可以在此处查看它的实际操作:http://jsfiddle.net/jfriend00/7KF7V/
对于要实现此功能,必须在设置
.src
属性之前分配onload
处理函数,因为如果图像位于浏览器缓存中,onload 可能会在之前立即触发.onload
已分配,因此错过了该事件。The only way I know of to do it is to attach a load handler for each image and keep a count of how many have been loaded. When you reach your total, then they've all been loaded.
Here's code that does that:
You can see it in action here: http://jsfiddle.net/jfriend00/7KF7V/
For this to work, the
onload
handler function has to be assigned before the.src
property is set because if the image is in the browser cache, onload may fire immediately before.onload
is assigned, thus missing the event.