如何使用 jQuery live() 进行 img onload 事件?
我想在加载图像时运行一些代码。另外,我想不引人注目地做到这一点(不是内联)。更具体地说,我想使用 jQuery 的 live()
函数,这样任何动态加载的图像都会发生这种情况。
我尝试过:
<img class="content_image" alt="" src="..." />
<script>
$('.content_image').live('load', function() {
alert('loaded!');
});
</script>
除了load
之外,我还尝试过onload
和onLoad
。当我替换为“点击”时,一切都按预期工作,所以我知道这不是一些干扰性的错误。
我无法找到 live() 函数的可用事件类型列表,因此据我所知,这可能是不可能的。
I want to run some code when an image is loaded. Also, I'd like to do it unobtrusively (not inline). More specifically, I want to use jQuery's live()
function so it will happen for any dynamically loaded images.
I've tried:
<img class="content_image" alt="" src="..." />
<script>
$('.content_image').live('load', function() {
alert('loaded!');
});
</script>
In addition to load
, I've tried onload
, and onLoad
. When I replace with 'click' all works as expected so I know it's not some interfering bug.
I haven't been able to find a list of available event types for the live()
function, so for all I know, it may not be possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(这将是
load
,而不是onload
或onLoad
。)load
不会冒泡(根据 < HTML5 中的 href="https://www.w3.org/TR/html5/embedded-content-0.html#the-img-element" rel="nofollow">img
条目规范,它是一个"简单事件",不会冒泡) ,因此您不能将其与live
或delegate
一起使用,它们依赖于从元素到其祖先元素的事件冒泡。您必须将其挂接到各个
img
元素上(并且在设置其src
之前执行此操作,否则您可能会错过它;并且始终记住要注意错误
)。 (是的,您确实可能会错过它:浏览器不是单线程的,只是 JavaScript 主线程。如果您设置了src
并且图像在缓存中或变得可用很快,浏览器就可以触发事件了。触发事件的方式是,浏览器查看事件触发时注册的处理程序,并在 JavaScript 主线程返回浏览器时对要调用的处理程序进行排队。如果没有注册处理程序,则 .没有排队,你永远不会得到回调。)(It would be
load
, notonload
oronLoad
.)load
doesn't bubble (according to theimg
entry in the HTML5 spec, it's a "simple event", which don't bubble), so you can't use it withlive
ordelegate
, which rely on the event bubbling from an element to its ancestor element(s).You'll have to hook it on the individual
img
elements (and do so before you set theirsrc
, since otherwise you can miss it; and always remember to watch forerror
as well). (Yes, you really can miss it: The browser is not single-threaded, just the JavaScript main thread. If you setsrc
and the image is in cache or becomes available soon enough, the browser can fire the event. The way events are fired is that the browser looks to see what handlers are registered as of when the event is fired, and queues those to be called when the JavaScript main thread yields back to the browser. If there are no handlers registered, they aren't queued, and you never get the callback.)它有点脏,但它有效:
it's a little bit dirty, but it works :
最后我偶然发现了这个 jQuery 插件:
https://github.com/desandro/imagesloaded
Finaly I stumbled upon this jQuery plugin :
https://github.com/desandro/imagesloaded