Is this a valid test to check if a URL refers to an Image in JS/jQuery
$(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)?
UPDATE
The next step will be: how can I encapsulate this logic into a function. I tried this -> http://jsfiddle.net/wp7Ed/2/
$(function() {
function IsValidImageUr开发者_如何学Gol(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?
You cannot ever turn an asynchonous call into a synchronous one in javascript.
error
and load
are asynchronous events, so you have to do it like this:
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
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);
I think yes because an error
event 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!
.
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';
});
精彩评论