javascript 如何处理 img 标签和其他标签上的 onLoad 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7356023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to handle onLoad Event on img tag and others
提问by rkmax
how to handle onLoad
Event on img tag?
如何处理onLoad
img 标签上的事件?
example:
例子:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
is like the imageLoader
就像 imageLoader
and others tags like script, link, etc...
和其他标签,如脚本、链接等...
回答by Joe
jQuery callback on image load (even when the image is cached)
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Seems to work for me, and should fix the caveat with caching.
似乎对我有用,并且应该通过缓存解决这个问题。
回答by jfriend00
There's an example of how to do this right on the jQuery doc page for .load().
在.load()的jQuery 文档页面上有一个如何正确执行此操作的示例。
HTML:
HTML:
<img src="book.png" alt="Book" id="book" />
Javascript:
Javascript:
$('#book').load(function() {
// Handler for .load() called.
});
And, there are a bunch of caveats to watch out for listed on that jQuery page too.
而且,该 jQuery 页面上也列出了许多需要注意的警告。
With images, if you want to assure that the load handler gets called, the load handler has to be set before the image can possibly be loaded. If you're constructing the image in code, that means you have to set the load handler before you set the .src
attribute. That's because, in some browsers, if the image is in the memory/disk cache, it will load immediately when you assign .src
and if you then subsequently set the .load()
handler, you will be too late (the image will already be loaded) and the .load()
handler will never be called.
对于图像,如果您想确保调用加载处理程序,则必须在加载图像之前设置加载处理程序。如果您在代码中构建图像,则意味着您必须在设置.src
属性之前设置加载处理程序。这是因为,在某些浏览器中,如果图像在内存/磁盘缓存中,它会在您分配时立即加载.src
,如果您随后设置.load()
处理程序,则为时已晚(图像已被加载)和.load()
处理程序永远不会被调用。
I don't know how to guarantee that a jQuery-based .load() always gets called for an image that's in your page HTML because you can't assign the event handler until the object exists, but once the object it exits, it might already be loaded. You can use non-jQuery setting of an onload=xxx in the actual HTML though that is an older style of coding. Of course, you can always hook window.onload to know when all page images (and other resources) have been loaded.
我不知道如何保证基于 jQuery 的 .load() 总是为页面 HTML 中的图像调用,因为在对象存在之前您无法分配事件处理程序,但是一旦对象退出,它可能已经加载。您可以在实际 HTML 中使用 onload=xxx 的非 jQuery 设置,尽管这是一种较旧的编码风格。当然,您始终可以挂钩 window.onload 以了解所有页面图像(和其他资源)何时已加载。