且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery回调图像加载(即使图像被缓存)

更新时间:2023-08-28 21:27:10

如果 src 已经设置好,然后事件在缓存的情况下触发,然后才绑定事件处理程序。要解决此问题,您可以根据 .complete 循环检查并触发事件,如下所示:

If the src is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this:

$("img").one("load", function() {
  // do stuff
}).each(function() {
  if(this.complete) $(this).load();
});

请注意 .bind() .one() 因此事件处理程序不会运行两次。

Note the change from .bind() to .one() so the event handler doesn't run twice.