2014-01-29 32 views
0

我有多個圖像的頁面,全部用類.listImage更換空SRC與圖片網址 - JQuery的

<img src="/path/to/image1.png" class="listImage"> 
<img src="/path/to/image2.png" class="listImage"> 
<img src="" class="listImage"> 
<img src="/path/to/image3.png" class="listImage"> 

在某些情況下,這些實際上可能沒有一個.src價值,所以我想替換任何唐沒有虛擬形象。

這裏就是我想但由於某種原因不能正常工作:如果

$().ready(function() { 
    $('.listImage').each(function() { 
     if (this.src.length == 0) { 
      $(this).attr('src','/images/img_blank.png'); 
     } 
    }); 
}); 

回答

4

試試這個使用attribute selector

$().ready(function() { 
    $('.listImage[src=""]').attr('src','/images/img_blank.png'); 
}); 
+1

** + 1 **不選擇不需要的'',perfect =) – MackieeE

+0

真棒 - 如何將5行切爲1 - 很好的教訓,謝謝 –

+0

因此,使用屬性選擇器實際上增加了如果在同一行中,優秀! –

0

不知道這是你的問題,但。 。 。

變化$()$(document)

這樣做解決?

如果不嘗試。 。 。

$(document).ready(function() { 
    $('.listImage').each(function() { 
     if($(this).attr("src") == "#") { 
      $(this).attr('src','/images/img_blank.png'); 
     } 
    }); 
}); 

更改空src屬性值#

0

使用此條件

if (this.attr("src").length == 0) { 

試試這個:

$(document).ready(function() { 
    $('.listImage').each(function() { 
    if (this.attr("src").length == 0) { 
     $(this).attr('src','/images/img_blank.png'); 
    } 
    }); 
}); 
0

使用:

$('.listImage').each(function() { 
    if ($(this).attr('src') == '') { 
     $(this).attr('src','/images/img_blank.png'); 
    } 
}); 
0

試試這個

$(document).ready(function(){ 
    $('.listImage').each(function (index,value) { 
     if ($(value).attr('src')=='') { 
      $(value).attr('src','notfound.png'); 
     } 
    }); 
} 
0

萬一你使用的是像數據src屬性,而不是SRC。這會工作:

$('.listImage').each(function() { 
    if (!hasAttr('src')) { 
    temp_attr = $(this).attr('data-src'); //temporary attribute for your src 

     $(this).attr('src',temp_attr); //Create src attribute with your value 

    $(this).removeAttr('data-src'); //remove temporary attribute to clean up stuff. 
    } 
}); 

從上面的代碼,如果你正在使用img標籤是這樣的:

<img data-src="image.png">

將轉換爲與src屬性這樣的img標籤:

<img src="image.png">

希望這會有所幫助!

0

這裏是

$(document).ready(function() { 
    $('.listImage').each(function (index,i) { 
     alert(index) 
     if ($(".listImage:eq("+index+")").attr("src").length == 0) { 
       $(".listImage:eq("+index+")").attr('src','/images/img_blank.png'); 
     } 
    }); 
}); 
0

也看到這個代碼

$('.listImage').each(function() { 
    if ($(this).attr("src")=="") { 
     $(this).attr('src','/images/img_blank.png'); 
    } 
});