在完成所有图像加载事件后,如何使这个jQuery插件可链接?

时间:2011-11-25 20:22:57

标签: jquery jquery-plugins

[更新]解决方案我决定:

决定在所有图片完成加载后,将回调传递给插件将负责触发事件。链接仍然是可能的。 Updated Fiddle


我正在构建一个可链接的jQuery插件,可以动态加载图像。

(将以下代码视为JSFiddle

HTML

<img data-img-src="http://www.lubasf.com/blog/wp-content/uploads/2009/03/gnome.jpg" style="display: none" />

<img data-img-src="http://buffered.io/uploads/2008/10/gnome.jpg" style="display: none" />

我没有添加src属性,而是为这些图片添加了data-img-src属性。我的插件使用其值来填充src。此外,这些图像一开始就是隐藏的。

jQuery插件:

(function(jQuery) {
jQuery.fn.loadImages = function() { 
    var numToLoad = jQuery(this).length;
    var numLoaded = 0;
    jQuery(this).each(function() { 
        if(jQuery(this).attr('src') == undefined) {
            return jQuery(this).load(function() {
                numLoaded++;
                if(numToLoad == numLoaded)
                    return this; // attempt at making this plugin 
                                 // chainable, after all .load()
                                 // events have completed.
            }).attr('src', jQuery(this).attr('data-img-src'));
        } else {
            numLoaded++;
            if(numToLoad == numLoaded)
                return this; // attempt at making this plugin 
                             // chainable, after all .load()
                             // events have completed.
        }
    });
    // this works if uncommented, but returns before all .load() events have completed
    //return this;
};
})(jQuery);


// I want to chain a .fadeIn() after all images have completed loading
$('img[data-img-src]').loadImages().fadeIn();

有没有办法让这个插件可链接,并且在所有图片加载后发生fadeIn()

4 个答案:

答案 0 :(得分:2)

与上述RedWolves一样,您应该使用:

return this.each(function() { //.....

以便您的代码可以链接。

您提到要在所有内容都已加载时执行此操作。为此,您应该将代码包装在jQuery的$()函数中,该函数采用内联的匿名函数,该函数将在DOM加载时执行。

所以在你的情况下,它将是:

jQuery(function($){    // jQuery is the same as $, and it passes itself to the function
    $('img[data-img-src]').loadImages().fadeIn();
});

答案 1 :(得分:1)

  1. 您不需要在jQuery函数中包装它。这已经指向了jQuery对象。

  2. 返回这将返回jQuery对象,使其可以链接,所以在这一行

  3. jQuery(this).each(function(){

    将其替换为

    返回this.each(function(){

    这将使您的插件可链接查看Authoring guide for more help

答案 2 :(得分:1)

使load()调用同步执行的唯一方法是事先用

设置它
$.ajaxSetup({
  async: false
});

这将暂停代码执行,直到加载完成,然后您可以正常返回。

http://jsfiddle.net/jXjT7/31/

答案 3 :(得分:0)

安德鲁是正确的,没有办法推迟对链接功能的调用,比如“fadeIn&#39;在您的示例中,除非使用同步ajax请求加载。不太适用于图片标签加载等等......

但他忘记了一个有趣的细节......像fadeIn这样的动画方法在调用时不会立即执行动画,而是使用动画队列。所以在你的情况下,你真的不介意如果立即调用fadeIn,你只需要暂停动画队列,直到图像被加载。

您可以这样做,例如在调用插件时执行.delay(1000000000),然后在加载图像时执行.stop()。

更政治正确的方法是执行相同的操作而不是.delay()到.queue()一个存储其第一个参数的函数,而不是.stop()在加载图像时调用存储的参数。

编辑:你的固定小提琴jsfiddle.net/jXjT7/42 /

相关问题