jquery 检查 img 是否有 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19360902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery check if img has src
提问by Sam Skirrow
I have a carousel of images that are dynamically populated. There is potential for up to 5 images, however, if there is less than 5 images I need to introduce some if statements in my code. Is it possible using jQuery to check if an img src is blank?
我有一个动态填充的图像轮播。最多可能有 5 个图像,但是,如果图像少于 5 个,我需要在我的代码中引入一些 if 语句。是否可以使用 jQuery 检查 img src 是否为空?
For example, if I have an image with class "optional" but it has no url, is there a way to detect this with jQuery?
例如,如果我有一个类为“可选”的图像但它没有 url,有没有办法用 jQuery 检测到它?
<img class="optional" src="" />
回答by Anton
Try this
尝试这个
$('.optional').each(function () {
if (this.src.length > 0) {
//if it has source
}
});
回答by undefined
You can use attribute selector:
您可以使用属性选择器:
$('img.optional[src=""]');
In case that you want select the images that don't have empty src
attributes:
如果您想选择没有空src
属性的图像:
$('img.optional[src!=""]');
回答by Rituraj ratan
回答by Guillaume Lehezee
JQUERY :
查询:
if($('img.optional').attr('src') != "") {
// Image has src !
} else {
// Image has not src :'(
}
回答by Urooj Khan
You can use
您可以使用
img[src=""] {
display: none;
}
The above selector will simply match, if the src attribute has no value.
如果 src 属性没有值,上面的选择器将简单匹配。