2012-03-06 81 views
0

我有一個圖片網址(http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zow)。我想驗證這在JavaScript中是否圖像存在或不。請幫助我找到解決方案。驗證圖片網址

+0

可能重複我該如何檢查在jQuery或Javascript?](http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascr IPT) – Curt 2012-03-06 10:05:43

回答

0

您的文章與之前由anothershrubery發佈的Change image source if file exists幾乎相同。

你可以試試這個

<img src="http://mydomain.com/images/image1.jpg" onerror="this.src='http://mydomain2.com/images/image1.jpg'" /> 

或者

<script language="JavaScript"><!- 
function testImage(URL) { 
var tester=new Image(); 
tester.onLoad=isGood; 
tester.onError=isBad; 
tester.src=URL; 
} 

function isGood() { 
alert('That image exists!'); 
} 

function isBad() { 
alert('That image does no exist!'); 
} 
//--></script> 
1

可以在一個隱藏的DIV加載圖像並檢查圖像加載。 我建議你使用jQuery來實現這一點。

負載事件延伸閱讀:http://api.jquery.com/load-event/

HTML:

<div id="image-container" style="display: none"> 
    <img src="http://your/image/url"> 
</div> 

的Javascript/jQuery代碼:

$('img', '#image-container ').load(function() { 
     // image loaded 
    }); 
2
try { 
var img = document.createElement("img"); 
img.src ="http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zowsd"; 

} catch(err) 
{ 
    // 
} 

if(img.height > 0) { 
//image exists 
} else { 
// image not exists 
} 
如果文件存在的[