2014-09-01 192 views
0

我已經得到這段代碼自動從創建「相冊」目錄加載照片。目錄命名爲:1,2,3,4,5等,其中的照片爲1.JPG,2.JPG,3.JPG等。我將它們加載到div元素中(tytul是存儲div的id,它們是phot1,phot2等的變量)。現在是我的問題,如果有,如何隱藏一個div,例如,沒有圖像6.JPG?jquery圖像自動加載

var numbopht = 20; 
var numbosubgals = 3; 
var activegal = numbosubgals; 
var leftnumber = 1; 

var idnam = []; 
//var idname = "#phot" + 


    var idunderline = "#subgal" + numbosubgals; // subgal to id pozycji na liście 




loadContent = function(i){ 

    var tytul = "#phot" + i; 
var photurl = "../photos/" + activegal + "/" + i + ".JPG"; 
var img = $("<img />").attr({ 
src: photurl, 
width:"120", 
height:"90" 

}); 
    $(tytul).empty().html(img); 


}; 

有些事情是不同意這種

 <div id="scrollbar"> 
      <div id="phot20" class="photon"></div> 
      <div id="phot19" class="photon"></div> 
      <div id="phot18" class="photon"></div> 
      <div id="phot17" class="photon"></div> 
      <div id="phot16" class="photon"></div> 
      <div id="phot15" class="photon"></div> 
      <div id="phot14" class="photon"></div> 
      <div id="phot13" class="photon"></div> 
      <div id="phot12" class="photon"></div> 
      <div id="phot11" class="photon"></div> 
      <div id="phot10" class="photon"></div> 
      <div id="phot9" class="photon"></div> 
      <div id="phot8" class="photon"></div> 
      <div id="phot7" class="photon"></div> 
      <div id="phot6" class="photon"></div> 
      <div id="phot5" class="photon"></div> 
      <div id="phot4" class="photon"></div> 
      <div id="phot3" class="photon"></div> 
      <div id="phot2" class="photon"></div> 
      <div id="phot1" class="photon"></div> 
     </div> 

其他的東西互動

回答

0

方法1:

使用檢查圖像的功能存在與否:

function imageExists(image_url){ 
var http = new XMLHttpRequest(); 
http.open('HEAD', image_url, false); 
http.send(); 
return http.status != 404; 
} 

使用函數來執行進一步的動作:

$.get(image_url) 
.done(function() {  // Image exists at specified URL and set properties 
var img = $("<img />").attr({ 
src: photurl, 
width:"120", 
height:"90" 
}); 

}).fail(function() { // Image does not exist so Hide the Div 
    $("#tytul").hide(); 
}) 

方法2:使用onerror事件的img

myImage.onerror = function(){ 
document.getElementById("tytul").style.display = 'none'; 
} 
+0

我對這個解決辦法太笨;/ – 2014-09-01 21:51:38

+0

方法2是很容易的。你只需要爲圖像創建一個'onerror'處理程序。當圖像加載失敗時調用'onerror'。因此,在'onerror'處理程序中簡單地設置'Display:None'來隱藏** tytul ** div。 – 2014-09-01 21:58:29

+0

@TomaszMałachowski:這是一個很少有代碼的工作示例。 [DEMO](http://codepen.io/anon/pen/uilve) – 2014-09-01 22:02:51

0

編輯,更新

嘗試

V3

$("#scrollbar div[id*=phot]:not(:has(img))").hide() 

的jsfiddle http://jsfiddle.net/guest271314/8x9bvhnj/

+0

它隱藏了所有圖片,不僅僅是破碎的圖片 – 2014-09-01 21:21:16

+0

@TomaszMałachowski請參閱OP at,「現在是我的問題如何在存在,例如,沒有圖像6.JPG?「是否需要隱藏具有屬性「6.JPG」或「img」父容器的'img'?如果可能,可以發佈'html'?謝謝 – guest271314 2014-09-01 21:34:55

+0

好的,添加HTML – 2014-09-01 21:48:06