-4
我正在將圖像的路徑推入數組中以隨機加載它們。我想檢查路徑是否包含圖像。我不使用圖片標籤orelse onerror事件會給我一個解決方案。那麼,有沒有辦法檢查路徑是否包含使用JavaScript的圖像?檢查路徑是否包含使用javascript的圖像
在此先感謝。
我正在將圖像的路徑推入數組中以隨機加載它們。我想檢查路徑是否包含圖像。我不使用圖片標籤orelse onerror事件會給我一個解決方案。那麼,有沒有辦法檢查路徑是否包含使用JavaScript的圖像?檢查路徑是否包含使用javascript的圖像
在此先感謝。
我在想是這樣的:
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.
}
你到目前爲止嘗試過什麼? – Wishnu
請告訴我們你到目前爲止所嘗試過的。 – Sumurai8
您創建一個圖像,看看它是否成功。看到這個線程:http://stackoverflow.com/questions/3744266/how-can-i-test-if-a-url-is-a-valid-image-in-javascript – Reason