1

次のようなプラグインがあります。

(function($){
  $.fn.extend({
    myplugin: function () {
      var jobs = [];
      this.each(function(){
        jobs.push($(this).one(
          'load',
          function(){
            // Line A: "Load" fires here
            // Replace image source
            $(this).attr('src','new_url');
            // Line B: Everything is done, fire now!
          }));
        });
        // Callback
        $.when.apply(null,jobs).then(function(){
          alert($(this).attr('src'));
        });
        return this;
      }
    });
  })(jQuery);

whenヘルパーは常に古いイメージ ソースを警告します。Line Aで呼び出されているためloadです。しかし、 Line Bで起動する必要があります。

これを解決するには?何か案は?

ありがとうございました!

4

1 に答える 1

4

遅延オブジェクトを に渡していませんwhen。渡すのは jQuery オブジェクトの配列だけです。

deferredコレクション内のすべてのアイテムに対して新しいものを作成し、次にresolveイベント リスナー内で作成します。

(function($){
    $.fn.myplugin = function () {
        var deferreds = [];

        this.each(function() {
            var deferred = $.Deferred();

            deferreds.push(deferred);

            $(this).one('load', function() {
                this.src = 'new_url';
                deferred.resolve();
            });
        });

        $.when.apply($, deferreds).then(function() {
            alert('All sources have been changed.');
        });

        return this;
    };
})(jQuery);

より簡潔にするために、代わりに関数を遅延コンストラクターに渡すことができます。

this.each(function (i, element) {
    deferreds.push( $.Deferred(function (deferred) {

        $(element).one('load', function() {
            this.src = 'new_url';
            deferred.resolve();
        });

    }));
});
于 2013-01-20T06:42:40.480 に答える