通过通配符查明url中是否存在图像

时间:2015-01-14 10:53:17

标签: javascript jquery

我正在尝试显示图像,但如果不存在,则还原为默认图像。但图像可以有任何图像扩展。那么如何在下面的$.get()函数中添加通配符,使其查找具有正确文件名的任何文件?

$.get('path/to/file.*')
    .done(function() {

    }).fail(function() {

    });

2 个答案:

答案 0 :(得分:1)

当src失败时,img元素会引发error事件。因此,您可以使用以下jQuery而无需AJAX请求(这意味着将生成nImages + 1个请求):

$('img').on('error', function() {
    $(this).prop('src', '/path-to/default-image.png');
});

答案 1 :(得分:0)

将尝试扩展列表的解决方案,如果无效则将应用默认图像

var validImageExtensions = ['jpg','png','gif'];

function imageOrDefault( path, defaultPath, target, index ){
    var img = $('<img>'),
        extensionIndex = index || 0;

    $(img)
        .on('load', function(){
            target.prop('src', img.prop('src'));
        })
        .on('error', function(){
            if (extensionIndex === validImageExtensions.length){
                target.prop('src', defaultPath);
            } else {
                imageOrDefault( path, defaultPath, target, extensionIndex +1);
            }
        });
    img.prop('src', path + '.' + validImageExtensions[extensionIndex]);
}

用法

imageOrDefault('path/to/image/without-extension', 'path/to/default.png', $('.target-selector'));