javascript 这是检查 URL 是否引用 JS/jQuery 中的图像的有效测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4669111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:29:15  来源:igfitidea点击:

Is this a valid test to check if a URL refers to an Image in JS/jQuery

javascriptjquery

提问by Jiew Meng

$(function() {
    $("<img>", {
        src: "http://goo.gl/GWtGo",
        error: function() { alert("error!"); },
        load: function() { alert("ok"); }
    });
});

Got inspiration from How can I test if a URL is a valid image (in javascript)?

如何测试 URL 是否为有效图像(在 javascript 中)中获得灵感

UPDATE

更新

The next step will be: how can I encapsulate this logic into a function. I tried this -> http://jsfiddle.net/wp7Ed/2/

下一步将是:我如何将这个逻辑封装到一个函数中。我试过这个 - > http://jsfiddle.net/wp7Ed/2/

$(function() {
    function IsValidImageUrl(url) {
        $("<img>", {
            src: url,
            error: function() { return false; },
            load: function() { return true; }
        });
    }
    alert(IsValidImageUrl("http://goo.gl/GWtGo"));
    alert(IsValidImageUrl("http://error"));
});

but of course it fails... how can I return from an internl event handler? Or how can I implement this?

但当然它失败了......我如何从内部事件处理程序返回?或者我该如何实现?

回答by Martin Jespersen

You cannot ever turn an asynchonous call into a synchronous one in javascript.

在 javascript 中,您永远无法将异步调用转换为同步调用。

errorand loadare asynchronous events, so you have to do it like this:

error并且load是异步事件,所以你必须这样做:

function IsValidImageUrl(url) {
    $("<img>", {
        src: url,
        error: function() { alert(url + ': ' + false); },
        load: function() { alert(url + ': ' + true); }
    });
}

IsValidImageUrl("http://goo.gl/GWtGo");
IsValidImageUrl("http://error");

or you can parse in callback function you define elsewhere like this:

或者您可以解析您在其他地方定义的回调函数,如下所示:

function myCallback(url, answer) {
    alert(url + ': ' + answer);
}

function IsValidImageUrl(url,callback) {
    $("<img>", {
        src: url,
        error: function() { callback(url, false); },
        load: function() { callback(url, true); }
    });
}

IsValidImageUrl("http://goo.gl/GWtGo", myCallback);
IsValidImageUrl("http://error", myCallback);

The clean and performant version skips the jQuery overhead like this

干净且高性能的版本跳过了这样的 jQuery 开销

function myCallback(url, answer) {
    alert(url + ': ' + answer);
}

function IsValidImageUrl(url, callback) {
    var img = new Image();
    img.onerror = function() { callback(url, false); }
    img.onload =  function() { callback(url, true); }
    img.src = url
}

IsValidImageUrl("http://goo.gl/GWtGo", myCallback);
IsValidImageUrl("http://error", myCallback);

回答by Sarfraz

I think yes because an errorevent is fired when image is not found. As in your code, if image is not found (meaning not a valid path to an image), the alert will come up with message error!.

我认为是的,因为error找不到图像时会触发一个事件。与您的代码一样,如果找不到图像(意味着不是图像的有效路径),警报将出现 message error!

Here is another version of how it might look:

这是它的外观的另一个版本:

$('#imgID').error(function(){
  alert('image not found !');
});

You can also change the path of your image in case previously specified image was not found like this:

如果未找到先前指定的图像,您还可以更改图像的路径,如下所示:

$('#imgID').error(function(){
   this.src = 'new path to some image';
});