如何使用jQuery live()进行img onload事件? [英] How to use jQuery live() for img onload event?

查看:158
本文介绍了如何使用jQuery live()进行img onload事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在加载图像时运行一些代码。另外,我希望不干涉(不内联)。更具体地说,我想使用jQuery的 live()函数,这样它就会发生在任何动态加载的图像上。



我试过了:

 < img class =content_imagealt =src =.../> ; 
< script>
$('。content_image')。live('load',function(){
alert('loaded!');
});
< / script>

load 外,尝试 onload onLoad 。当我用'点击'替换所有的作品,所以我知道这不是一些干扰性的bug。



我还没有找到可用的事件类型列表 live()函数,所以我知道,这可能是不可能的。 (它会是 load ,而不是 onload onLoad )
$ b $ load 不会冒泡(根据 img 入门HTML5规范,它是简单事件 ,它不会冒泡),所以你不能在 live 委托中使用它,它依赖于事件从元素冒泡到它的祖先元素。



你必须把它挂在单独的 img 元素(并在之前你可以设置它们的 src ,否则你可能会错过它;并且始终记得要注意 error )。 (是的,你真的可能会错过它:浏览器不是单线程的,只是JavaScript主线程。如果你设置 src 并且图像在浏览器可以触发事件的情况下,事件被触发的方式是浏览器在触发事件时查看哪些处理程序被注册,并在JavaScript主要时候排队这些事件线程退回到浏览器,如果没有注册的处理程序,它们不会排队,并且你永远不会收到回调。)


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.

解决方案

(It would be load, not onload or onLoad.)

load doesn't bubble (according to the img entry in the HTML5 spec, it's a "simple event", which don't bubble), so you can't use it with live or delegate, 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 their src, since otherwise you can miss it; and always remember to watch for error as well). (Yes, you really can miss it: The browser is not single-threaded, just the JavaScript main thread. If you set src 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.)

这篇关于如何使用jQuery live()进行img onload事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆