2012-09-03 275 views
1

我有一個真正簡單的jQuery顯示功能,當單擊鏈接時將圖像加載到DIV中。jQuery顯示 - 默認圖像

$(function(){ 
jQuery(".gallery-item a").click(function(evt) { 
    evt.preventDefault(); 
    jQuery("#imageBox").empty().append(
     jQuery("<img>", { src: this.href}) 
    ); 
}); 
}); 

有沒有辦法添加一個默認圖像,以便當一個頁面加載的時候有一個圖像在div中已經?

+0

你就不能添加到HTML? – MarcoK

+0

只需在頁面加載時點擊第一個「」即可。 – adeneo

回答

1
$(function() { 
    $(".gallery-item a").click(function (evt) { 
     evt.preventDefault(); 
     var box = $("#imageBox").html('<img src="default.jpg" />'); 

     $("<img>", {src: this.href}).load(function() { 
      box.empty().append(this); 
     }); 
    }); 
}); 
+0

我從這個沒有得到任何東西,直到我點擊其中一個鏈接,然後默認圖像顯示一秒之後被替換爲我點擊的那個? – fightstarr20

0

試試這個:

$(function() { 
    jQuery(".gallery-item a").click(function(evt) { 
     jQuery("#imageBox").empty().append(
      jQuery("<img />", { src: $(this).attr("href") }) 
     ); 
     return false; 
    }); 
});​ 

編輯發表評論:

假設圖像的URL是在屬性 「數據urlimage」 標籤 「一」

Html:

<div class="gallery-item"> 
<a data-urlimage="/img/myimage.jpg" href="#">click here</a> 
</div> 

的Javascript:

$(function() { 
    jQuery(".gallery-item a").click(function(evt) { 

     var img = new Image(); 
     img.src = $(this).data("urlimage"); 
     img.onload = function(){ 
      jQuery("#imageBox").empty().append(img); 
     }; 

     return false; 
    }); 
});​ 

see image events

編輯:看看如何創造更好的對象 「圖像」

+0

用這種方法,我會在哪裏放置圖像的網址?我會替換href嗎? – fightstarr20

+0

我認爲你有標籤「a」的「href」屬性中的圖像的網址。如果你可以替換你想要的「href」 –