如何使用jQuery检查图像URL是否为空并执行某些操作


How to Check with jQuery if Image URL is Empty and Do something?

我正在使用PHP从另一个站点加载XML提要。我在 HTML 中的输出是这样的:

<div class="sponsored">
<div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div> 
<div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div>
<div class='box'><img src='http:///xxx.jpg'><a href='xxx/'>Title</a></div>
<div class='box'><img src=''><a href='xxx'>Title</a></div>   
</div>

最后一部分没有 src 网址,这意味着提要没有提供任何图像。我想用jquery检查这个HTML输出,以检查是否有src url。如果是这样,那么放置 defauly 图像以获得更好的格式。

我看到了检查div中图像的jquery脚本。但是有没有办法检查图像src是否为空?

====

============

更新:

好的,我不确定为什么它以前不起作用。最后,下面的代码适用于我:

$(".sponsored > .box > img[src='']").attr("src","default.png");

谢谢大家的回答!!这是像我这样的未来菜鸟的最终工作代码:)

<script>
$(document).ready(function(){
$(".sponsored > .box > img[src='']").attr("src","image.jpg");
});
</script>
你可以

attribute equals选择器来做到这一点,

$(".sponsored > .box > img[src='']").attr("src","default.png");
$(document).ready(function(){
    $(".sponsored .box img").each(function(){
        if($(this).attr('src') == ''){
            $(this).attr('src') = 'default.png';
        }
    });
});
你可以

这样使用,这个例子会给你3 not empty记录和1 empty记录,你可以在浏览器控制台中检查结果:

$('.box img').each(function(index,val){
    if($(this).attr('src') == ''){
      console.log('empty');
    }
    else{
     console.log('not empty');
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sponsored">
<div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div> 
<div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div>
<div class='box'><img src='http:///xxx.jpg'><a href='xxx/'>Title</a></div>
<div class='box'><img src=''><a href='xxx'>Title</a></div>   
</div>

试试这个

$('.box img').each(function(){
if($(this).attr('src') == ''){
  //do something
}
else{
  //do something
}
});
$('.sponsored .box img').each(function () {
    if (this.src!== undefined && this.src!='') {
        console.log("Exists");
    }else
    {
        console.log("Not Exists");
    }
});