如何从foo获得响应.Onload = function(){

How to get response from foo.onload = function(){?

本文关键字:function Onload 响应 foo      更新时间:2023-09-26

我有一个使用.onload触发的函数。我想返回一个值:

newImg.onload = function() {
    var height = newImg.height;
    var width = newImg.width;
    if(height > width){
        console.log(false);
        return false;
    } else {
        console.log(true);
        return true;
    }
 }
 newImg.src = imgSrc; // this must be done AFTER setting onload

通常我会这样写

var foo = function(){...

但是在这种情况下不起作用。我该怎么办呢?

异步调用不能返回值。您需要像在Ajax请求中那样使用回调。

function loadImg (imgSrc, callback) {
    var newImg = new Image();
    newImg.onload = function() {
        var height = newImg.height;
        var width = newImg.width;
        if(height > width){
            console.log(false)
            if(callback) callback(false);
        } else {
            console.log(true)
            if(callback) callback(true);
        }
     };
     newImg.onerror = function () {
         if(callback) callback('error');
     };
     newImg.src = imgSrc;
}
loadImg("foo.gif", function(status) { console.log("Do Next Step"); })

您有两个选择;

  1. 将值设置为其他变量

    var foo;
    newImg.onload = function () {
        foo = true;
    };
    // Sometime later read `foo`.
    

    …尽管这很容易导致灾难,因为您不能保证何时设置变量,因为图像将花费一些时间来加载。

  2. 一个更好的选择是调用另一个函数,传递你想传递的值,然后相应地处理它。

    newImg.onload = function () {
        foo(true);
    };
    function foo(result) {
        // do something with result
    }