Javascript 如何从foo.onload=function()获取响应{?

Javascript 如何从foo.onload=function()获取响应{?,javascript,jquery,Javascript,Jquery,我有一个使用.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

我有一个使用.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(){...
但在这种情况下,这不起作用。我应该怎么做呢?

您有两个选择

将该值设置为另一个变量

var foo;

newImg.onload = function () {
    foo = true;
};

// Sometime later read `foo`.
…尽管这很容易发生灾难,因为您无法保证变量将在何时设置,因为加载映像将花费一些时间

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

newImg.onload = function () {
    foo(true);
};

function foo(result) {
    // do something with result
}
你有两个选择

将该值设置为另一个变量

var foo;

newImg.onload = function () {
    foo = true;
};

// Sometime later read `foo`.
…尽管这很容易发生灾难,因为您无法保证变量将在何时设置,因为加载映像将花费一些时间

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

newImg.onload = function () {
    foo(true);
};

function foo(result) {
    // do something with result
}

异步调用不能返回值。您需要像在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"); })

异步调用不能返回值。您需要像在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"); })

您有一些拼写错误,reurn false,您应该作为最佳实践使用;作为分隔符。如果您试图获取响应值,那么您就错过了面向事件编程的要点。您有一些拼写错误,reurn false,您应该作为最佳实践使用;作为分隔符。如果您试图获取响应值,则t如果你错过了面向事件编程的要点。太棒了!我该如何使用回调?添加了使用回调的基本示例太棒了!我该如何使用回调?添加了使用回调的基本示例