我正在将图像路径推入数组中以随机加载它们。我想检查路径是否包含图像。我没有使用image tag orelse,onerror事件会给我一个解决方案。那么,有没有办法检查路径是否包含使用javascript的图像?
提前致谢。
答案 0 :(得分:1)
我在考虑这样的事情:
var path = "here/there.jpg"; //Your path to the image.
var ext = path.substring((path.length-4), path.length);
//^ This gets the last four characters of the string 'path'.
if(ext == ".jpg"){
arr[yourIndexHere] = path; //Add the image path to the array you're using.
}else{
//Throw an error here.
}
我会检查每个图像的扩展名,看看它是否是已知的图像文件类型。
显然,如果您已经知道您仅使用.jpg
,则可以使用上述内容,但如果您不知道它可能是什么,则以下内容可以正常使用。
var path = "here/there.jpg"; //Your path to the image.
var ext = path.substring((path.length-4), path.length);
//^ This gets the last four characters of the string 'path'.
switch(ext){
case ".jpg":
//Array stuff here.
break;
case ".png":
//Array stuff here
break;
default:
//Do something else here - throw an error maybe.
}