简体   繁体   English

如何使用jQuery live()进行img onload事件?

[英]How to use jQuery live() for img onload event?

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. 更具体地说,我想使用jQuery的live()函数,因此任何动态加载的图像都会发生这种情况。

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 . 除了load ,我还尝试过onloadonLoad When I replace with 'click' all works as expected so I know it's not some interfering bug. 当我用'click'替换时,所有工作都按预期工作,所以我知道这不是一些干扰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. 我无法找到live()函数的可用事件类型列表,所以我知道,这可能是不可能的。

(It would be load , not onload or onLoad .) (这将是load ,而不是onloadonLoad 。)

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). load不会冒泡(根据HTML5规范中img条目 ,它是一个“简单事件” ,它不会冒泡),所以你不能将它用于livedelegate ,它依赖于从一个冒泡的事件元素到它的祖先元素。

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). 你必须将它挂钩到各个img元素上(并且设置它们的src 之前这样做,否则你可能会错过它;并且总是记得也要注意error )。 (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.) (是的,你真的可以错过它: 浏览器不是单线程的,只是JavaScript主线程。如果你设置src并且图像在缓存中或者很快就可用,浏览器可以触发事件。事件的方式是触发器是浏览器查看当事件被触发时注册的处理程序,并在JavaScript主线程返回浏览器时对要调用的处理程序进行排队。如果没有注册处理程序,则它们不排队,你永远不会得到回调。)

it's a little bit dirty, but it works : 它有点脏,但它有效:

<script type="text/javascript">
    var loop = setInterval(function() {

           // the img to watch
           var $img = $("img.hi");

           if( !!$img.length && $img[0].complete ) {
               // clear the timer
               clearInterval(loop);

               alert("loaded !");

           }

    }, 30);        
</script>

<img class="hi" src="http://www.google.fr/images/nav_logo72.png" />

最后我偶然发现了这个jQuery插件: https//github.com/desandro/imagesloaded

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM