加载图像,如果找到,否则加载另一个图像图像、加载

2023-09-10 13:17:33 作者:总被自己萌哭

我需要做的就是简单地说,但(我)很难做到的:

what I need to do is simple to say but (for me) hard to do:

使用的的javascript ,给定一个图像的名字,即image01.jpg,我需要检查,如果这一形象存在于一个特定的文件夹或路径(本地或网络上)。如果图像没有这个文件夹下存在的,我需要检查,如果相同的图像存在于另一个文件夹中。

using javascript, given an image name, ie "image01.jpg", I need to check if this image exists in a certain folder or path (local or on the web). If the image does not exist under that folder, I need to check if the same image exists in another folder.

例如,伪code

imageToFind = 'image01.jpg'
path1 = 'users/john/images'
path2 = 'users/mike/img'

if path1+'/'+imageToFind exists
    //do something
else
    if path2+'/'+imageToFind exists
        //do something
    else
        print('NOT FOUND')

你的建议是什么样的方式?我trye​​d首先使用AJAX,然后使用JavaScript的形象()来实现这一点,但我没有在这两种情况下。

what kind of approach do you suggest? I tryed to achieve this using ajax first, and then using javascript's Image() , but I failed in both these cases.

在此先感谢您的帮助,最好的问候

Thanks in advance for any help, best regards

推荐答案

您可以pretty的多依赖本地的onload 的onerror 事件处理这火的图像节点的。因此,它可能看起来像

You can pretty much rely on native onload and onerror event handlers which fire for Image nodes. So it could look like

var images = ['users/john/images/image01.jpg','users/mike/img/image01.jpg','some/more/path/image01.jpg'];

(function _load( img ) {
    var loadImage = new Image();

    loadImage.onerror = function() {
        // image could not get loaded, try next one in list
        _load( images.shift() );
    };
    loadImage.onload = function() {
        // this image was loaded successfully, do something with it
    };

    loadImage.src = img;
}( images.shift() ));

这code可能确实有点多,你居然问了。你基本上可以,但是尽可能多的图像路径的,你想进入这个数组,该脚本将搜索列表,直到它可以成功加载一个图像。

This code probably does a little more than you actually asked for. You can basically but as much image paths as you wish into that array, the script will search the list until it could load one image successfully.