如何处理 img 标签等上的 onLoad 事件
如何处理img标签上的onLoad
事件?
示例:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
就像 imageLoader
和其他标签,如脚本、链接等...
how to handle onLoad
Event on img tag?
example:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
is like the imageLoader
and others tags like script, link, etc...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
图像加载时的 jQuery 回调(即使图像已缓存)
似乎对我有用,并且应该修复缓存的警告。
jQuery callback on image load (even when the image is cached)
Seems to work for me, and should fix the caveat with caching.
.load() 的 jQuery 文档页面 上有一个如何正确执行此操作的示例。
HTML:
Javascript:
并且,该 jQuery 页面上也列出了许多需要注意的警告。
对于图像,如果您想确保调用加载处理程序,则必须在加载图像之前设置加载处理程序。如果您在代码中构建图像,这意味着您必须在设置
.src
属性之前设置加载处理程序。这是因为,在某些浏览器中,如果图像位于内存/磁盘缓存中,则当您分配.src
并且随后设置.load() 处理程序,你就来不及了(图像已经加载)并且
.load()
处理程序将永远不会被调用。我不知道如何保证基于 jQuery 的 .load() 始终会被调用用于页面 HTML 中的图像,因为在对象存在之前您无法分配事件处理程序,但是一旦对象存在,它就会可能已经加载。您可以在实际 HTML 中使用 onload=xxx 的非 jQuery 设置,尽管这是一种较旧的编码风格。当然,您始终可以挂钩 window.onload 来了解所有页面图像(和其他资源)何时已加载。
There's an example of how to do this right on the jQuery doc page for .load().
HTML:
Javascript:
And, there are a bunch of caveats to watch out for listed on that jQuery page too.
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.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 方法,而不是 onload。你的代码可能应该是:
jQuery has a load method, not onload. And your code should probably be: