检查图像是否存在

时间:2015-08-26 13:08:22

标签: javascript jquery

我正在使用.html()添加图片

$('#holder').html('<img class="holderClass" src="image.png" />');

现在我如何在if语句中检查图像是否存在?

我尝试了这个,但是做了吗?

if( ! $('.holderClass') ){ 
   console.log('image.png is there');
}

1 个答案:

答案 0 :(得分:2)

您正在使用代码中的!检查错误情况,这是错误的 同样对于jquery对象,您需要检查length以检查是否存在。

 if($('.holderClass').length > 0){ 
   console.log('image.png is there');
 }

或更具体地说

$('#holder > .holderClass').length > 0){ 
   console.log('image.png is there');
 }