2016-05-16 66 views

回答

1

您可以使用表達式來檢查文件的擴展名:

function checkURL(url) { 
    return(url.match(/\.(jpeg|jpg|gif|png)$/) != null); 
} 

檢查是否圖像可以通過使用這樣的功能加載的網址:

function testImage(url, callback, timeout) { 
    timeout = timeout || 5000; 
    var timedOut = false, timer; 
    var img = new Image(); 
    img.onerror = img.onabort = function() { 
     if (!timedOut) { 
      clearTimeout(timer); 
      callback(url, "error"); 
     } 
    }; 
    img.onload = function() { 
     if (!timedOut) { 
      clearTimeout(timer); 
      callback(url, "success"); 
     } 
    }; 
    img.src = url; 
    timer = setTimeout(function() { 
     timedOut = true; 
     callback(url, "timeout"); 
    }, timeout); 
} 

此功能將調用您在未來某個時間使用兩個參數進行回調:原始URL和結果(「成功」,「錯誤」或「超時」)。