【问题标题】:jQuery - receiving right variable value from handler function [duplicate]jQuery - 从处理函数接收正确的变量值
【发布时间】:2013-10-24 21:15:33
【问题描述】:

我正在编写 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 );

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

【问题讨论】:

  • 那是因为load 是异步的。在你给它的回调中做你需要做的事情。

标签: javascript jquery


【解决方案1】:

问题是当您执行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
});

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

【讨论】:

    【解决方案2】:

    Jquery.load 是一个异步调用。无论 Jquery.load 是否执行完毕,这个函数之后的所有代码都会被执行

    $(img).load(function(event)
                {      
                lastim=5;
    //DO ALL YOU WANT TO DO WITH YOUR VARIABLE HERE
                });
        });
    

    【讨论】:

      【解决方案3】:

      您的问题是:$(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 );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-20
        • 2021-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多