javascript返回事件

时间:2014-08-05 12:35:53

标签: javascript return

有几个类似于我的问题,但不幸的是我无法找到解决方案,但是: 我通过JS中的函数向网站添加图像,并希望返回可以加载或不加载图像的真/假。

好的,有JS onload和onerror事件。因此,很明显我无法在onload函数中使用return。但有没有办法给图像加载函数的父级返回?

这将是一种非常(非常非常)简单的方法:

function loadimage(source) {
    var image = new Image();
    var loaded = null;
    image.onload = function() {
        loaded = true;
    };
    image.onerror = function() {
        loaded = false;
    };
    image.src = source;
    return loaded;
}

在JS文件的某个地方,这个函数将被称为:

var isimageloaded = loadimage('http://i.stack.imgur.com/PIFN0.jpg');
console.log(isimageloaded) // true or false

毋庸置疑:这不起作用。但我希望它能说明我想做什么。

我猜解决方案是回调。但那会是什么样子? 谢谢你的时间!

0 个答案:

没有答案