[英]Hide image if src is empty
如果源為空,我試圖隱藏<img>
。 但我沒有運氣。
我在這里發現了一些帖子,但它對我不起作用。
這是我的代碼,它是基於表的,因為它將是一個模板:圖像:
<td width="92%" align="center" class="imagenes_desc">
<a href="#" class="showcase"><img class="imagen" src="http://webs.ono.com/norfolk/ebay/images/01.jpg" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
<a href="#" class="showcase"><img class="imagen" src="" width="800"></a>
</td>
這是我正在嘗試實現的Javascript。
<script type="text/javascript">
$(document).ready(function(){
if ($(".imagen").attr(src="") == "") {
$(".imagen").hide();
}
else {
$(".imagen").show();
}
</script>
我對JS不是很熟悉,我在Stackoverflow上找到了這個腳本,但我無法讓它工作。
更新
嘗試這個,但不起作用(Chrome隱藏得很好,但Firefox和IE卻沒有):
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type="text/javascript">
$("imagen").each(function(){
if ($(this).attr("src") == "")
$(this).hide();
else
$(this).show();
});
</script>
<style>
.hide {display:none !important;}
.show {display:block !important;}
</style>
謝謝,
您可以使用CSS:
img[src=""] { display: none; }
<img src=""> <img src="http://dreamatico.com/data_images/kitten/kitten-2.jpg">
你的邏輯是有缺陷的。
if ($(".imagen").attr(src="") == "") {
$(".imagen").hide();
}
else {
$(".imagen").show();
}
這是行不通的,因為你已遍歷.imagen
每個實例
$('.imagen').show().filter(function(){
return $(this).attr('src') == '';
}).parents('a').hide();
在上面,我們顯示所有.imagen
的,然后根據他們的src
屬性進行過濾,然后隱藏我們剩下的那個。
作為側點,您可能希望隱藏父<a>
元素,而不是圖像。
如何使用jQuery的屬性選擇器 ?
$(document).ready(function(){
$('.imagen[src=""]').hide();
$('.imagen:not([src=""])').show();
});
你有錯誤的語法來獲取src的值attr()
更改
if ($(".imagen").attr(src="") == "") {
至
$(".imagen").each(function(){
if ($(this).attr("src") == "")
$(this).hide();
else
$(this).show();
});
我很驚訝您沒有某種語法錯誤而且您的代碼也是錯誤的,因為它不會測試.imagen的每個實例。
像這樣做
$(".imagen[src='']").hide();
在樣式表中,添加以下代碼以定義“隱藏”類:
.hidden {
display: none;
}
然后添加以下javascript代碼:
$(document).ready(function() {
$(".imgagen").each(function() {
var atr = $(this).attr("src");
if(atr == "") {
$(this).addClass("hidden");
} else {
$(this).removeClass("hidden");
}
});
});
測試src屬性是否為null,但無論如何 - 如果你隱藏圖像包裝A元素會發生什么? 相反,不要為沒有任何圖像的人生成A / IMG元素。
您發布的代碼應該可以使用,但請確保您已在ur html頁面的標題上添加了jquery庫文件。
轉到jquery站點,然后下載js文件。 然后在HTML頁面部分頭部添加以下行:
只需將空間放在alt標簽內。這是工作代碼
<img class="imagen" src="" width="800" alt" ">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.