如何检测图像路径是否有效? [英] How to detect if the image path is valid?
本文介绍了如何检测图像路径是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我发现了一个关于图片的问题
I have found a question regarding the images
我试过以下代码
var image = new Image;
image.src = "http://project" + path + '.png';
image.onload = function(){
var imageWidth = this.width + this.height;
if(imageWidth==0){
image.src = "http://project2" + path + '.png';
//the project2 path could be broken too and
//I want to use project3 or project4 as the
//path and keep testing it, but there is no way to do it from here.
}
}
是否可以递归
在这里测试?非常感谢!
Would it be possible to do a recursive
test here? Thanks a lot!
推荐答案
您可以尝试以下设置:
var paths = ["/img1", "/img2", "/img3"];
var beginning = "http://project";
var ending = ".png";
function getImage(images, prefix, suffix, callback) {
var iterator = function (i) {
if (i < images.length) {
var image = new Image();
image.onload = function () {
var imageWidth = this.width + this.height;
if (imageWidth === 0) {
console.log("onload problem");
iterator(++i);
} else {
console.log("onload good");
callback(i, image);
}
};
image.onerror = function () {
console.log("onerror");
iterator(++i);
};
image.src = prefix + images[i] + suffix;
}
};
iterator(0);
}
getImage(paths, beginning, ending, function (index, img) {
console.log("Callback: ", index, ", ", img);
});
DEMO: http://jsfiddle.net/2mRMr/2/
这篇关于如何检测图像路径是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文