带返回的image.onload函数

时间:2011-09-15 16:36:22

标签: javascript image javascript-events

我有一个JS函数,其中计算了一个值,并且应该返回此值,但每次undefined都会得到,但如果我console.log(),则此函数中的结果可以正常工作。你能帮忙吗?

function detect(URL) {
    var image = new Image();
    image.src = URL;
    image.onload = function() {
        var result = [{ x: 45, y: 56 }]; // An example result
        return result; // Doesn't work
    }
}

alert(detect('image.png'));

5 个答案:

答案 0 :(得分:24)

返回值,但不返回detect函数。

如果对load事件处理程序使用命名函数而不是匿名函数,则更清楚发生了什么:

function handleLoad() {
  var result = [{ x: 45, y: 56 }];
  return result;
}

function detect(URL) {
  var image = new Image();
  image.src = URL;
  image.onload = handleLoad;
}

该值从handleLoad函数返回到调用事件处理程序的代码,但detect函数在此之前已经退出。 return函数中根本没有任何detect语句,因此您不能指望结果只是undefined

处理这种异步方案的一种常用方法是使用回调函数:

function detect(URL, callback) {
  var image = new Image();
  image.src = URL;
  image.onload = function() {
    var result = [{ x: 45, y: 56 }];
    callback(result);
  };
}

使用回调调用detect函数,一旦值可用,将调用该函数:

detect('image.png', function(result){
  alert(result);
});

答案 1 :(得分:3)

这是因为函数检测不返回任何内容,因为在函数完成后发生了加载事件。而且你忘了把图像附加到某个东西上,所以它永远不会加载。

您可以执行以下操作:

function detect(URL) {
    var image = new Image();
    image.src = URL;
    image.onload = function() {
        var result = 'result'; // An example result
        alert(result); // Doesn't work
    }
    document.body.appendChild(image)
}

detect('http://www.roseindia.net/javascript/appendChild-1.gif');

在这里摆弄http://jsfiddle.net/LVRuQ/

答案 2 :(得分:3)

我自己明白了:

我不知道我可以为其分配一个变量(对于我来说已经分配了)onload。

function detect(URL) {
    var image = new Image();
    image.src = URL;
    var x = image.onload = function() {
        var result = [{ x: 45, y: 56 }]; // An example result
        return result;
    }();
    return x;
}

alert(detect('x'));

答案 3 :(得分:2)

detect()不会返回任何值。如果您想收到提醒,请将return result;替换为alert(result)

对您的代码进行分析:

function detect(URL) {
    ...
    image.onload = function(){ //assigning an event handler (function) to an object
        ...
        return result; //this return statement is called from within another function
    }
}//function "detect" ends here. No return statement has been encountered

答案 4 :(得分:1)

您的函数detect不返回任何内容,这就是alert显示“未定义”的原因。您声明的return语句不起作用是从您分配给image.onload的匿名函数返回,如果您调用 函数,则可能正常。