2012-03-06 19 views
0

私は画像のURLを持っています(http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zow)。私はイメージが存在するかどうかをjavascriptで検証したいと思います。解決策を見つけるのを助けてください。画像のURLを確認

+0

の可能性の重複ファイルが存在する場合は、[どのようにチェックしますがjQueryまたはJavascriptで?](http://stackoverflow.com/questions/3646914/how-do-i-check-if-file-exists-in-jquery-or-javascr ipt) – Curt

答えて

0

あなたの投稿は以前にanothershruberyによって投稿されたChange image source if file existsとほぼ同じです。

あなたは隠されたDIVであなたのイメージをロードし、イメージがロードされたかどうかを確認することができ、この

<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

を試すことができます。 これを実現するためにjQueryを使用することをお勧めします。

はさらにLoadイベントで読ん: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 
}