带返回的image.onload函数 [英] image.onload function with return

查看:824
本文介绍了带返回的image.onload函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JS function where a value is computed and this value should be returned but I get everytime undefined but if I console.log() the result within this function it works. Could you help?

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'));


推荐答案

我自己拿到:

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

I didn't know that I can assign a variable to that (for me looking already assigned) 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'));

这篇关于带返回的image.onload函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆