回调函数可以是下一行代码

时间:2014-07-24 05:40:05

标签: javascript jquery function onload

Code:

     var getImageFromUrl = function(url, callback) {
      var img = new Image();

      img.onError = function() {
        alert('Cannot load image: "'+url+'"');
      };
      img.onload = function() {
        callback(img);
      };
      img.src = url;
    }
 getImageFromUrl(somurl, Nextline);
LINE1-//should come here  after callback(img)

我希望在img.onload函数之后,编译器将在line1中运行代码

1 个答案:

答案 0 :(得分:0)

实际上你可以使用JQuery Callback函数来做到这一点。

var getImageFromUrl = function(url, callback) {
  var img = new Image();

  img.onError = function() {
    alert('Cannot load image: "'+url+'"');
  };
  img.onload = function() {
    callback(img);
  };
  img.src = url;
}
var callBack = $.Callbacks();
callBack.add(getImageFromUrl(somurl, Nextline));
callBack.add(function(){
  // LINE 1 logic can be executed here.
 });

callBack.fire();

如需进一步参考,请参阅 here