jQuery - 从处理函数接收正确的变量值

时间:2013-10-24 13:04:39

标签: javascript jquery

我正在编写jQuery插件并遇到一个小问题 - 无法从事件的处理函数中获取变量。看看我的例子是为了理解:

(function( $ ){

  var methods = {

  init : function( options ) {

   var settings = $.extend( {
    'images': [['1.jpg'],['2.jpg'],['3.jpg']]
    }, options);

    var lastim=2; //just for test

    $.each(settings.images,function(event) {

    console.log(lastim); //Getting 2, Ok!

    img=new Image();
    img.src=settings.thumbPath+'/'+this[0];

    $(img).load(function(event)
            {      
            lastim=5;
            });
    });

    console.log(lastim); //Getting 2, expecting 5

   }};

$.fn.testSlider = function( method ) {
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'No such method'+method );
    } 
};

})( jQuery );

如何在每个函数后获得5个lastim变量?提前感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

问题是当您执行console.log(lastim);时未加载图像。

使用deferred对象或回调。

回调解决方案:

var methods = {
       loadImage: function(img, cb){
            $(img).load(cb);
       }

//.... etc

像这样使用:

methods.loadImage(img, function(){
    //image loaded
});

或者如果您更喜欢延迟对象:

var dfd = $.Deferred(),
    promise = dfd.promise();

$(img).load(function(event){      
    dfd.resolve();
}).error(function(){
    dfd.reject();
});

promise.done(funciton(){
    //image loaded successfully
}).fail(function(){
    //image load error
});

由于您在内部使用延迟,因此您可以跳过承诺并在dfd上使用相同的方法。

答案 1 :(得分:1)

Jquery.load是一个异步调用。无论Jquery.load是否已完成执行

,都将执行此函数之后的所有代码
$(img).load(function(event)
            {      
            lastim=5;
//DO ALL YOU WANT TO DO WITH YOUR VARIABLE HERE
            });
    });

答案 2 :(得分:0)

您的问题是:$(img).load(function(event)是异步的。退出该函数时,尚未调用回调函数。

尝试:

(function( $ ){

  var methods = {

  init : function( options, callback ) { //Pass in a callback to receive value

   //Your code 

    $(img).load(function(event)
            {      
               lastim=5;
               if (typeof callback === "function"){
                     callback(lastim);
               }
            });
    });

   }};

var callback = function(lastim){
           //get callback value here
};

$.fn.testSlider = function( method ) {
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1            ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments.concat([callback]);
    } else {
      $.error( 'No such method'+method );
    } 
};

})( jQuery );
相关问题