2013-01-25 94 views
1

問題加載圖像URL存儲在HTML5數據標籤與jQuery

當對某一圖像的縮略圖用戶點擊,圖像URL存儲在HTML5數據屬性data-url應加載,和功能性的其餘部分應繼續後。但是,我不知道如何讓圖像加載jQuery選擇器。

代碼

$(document).ready(function() { 
    $("img").on("click", function() { 

     var url = $(this).data("url"); 

     $('<img data-url="">').load(function() { 
      console.log("loaded"); 
      $("#wrapper").html('<img src="' + url + '">'); 
     }); 
    }); 
}); 

注意這是第一次加載圖像的縮略圖,並單擊時,jQuery的應該等到data-url屬性的圖像加載。一旦它被加載,它應該將該圖像注入#wrapper

回答

1

沒有測試,但它應該像這樣工作:

$(document).ready(function() { 
    $("img").on("click", function() { 
     // grep the data attribute 
     var url = $(this).data("url"); 
     if(url) { 
      // if it is an url, create an image 
      var img = $('<img />').appendTo('#Wrapper').hide(); 
      // set the src with the url 
      img.attr("src", url); 
      img.load(function() {  
       // if it is loaded, show the image 
       // and do whatever you want. 
       img.show(); 
      }); 
     } 
    }); 
}); 

了反對票我試圖代碼後,工作對我來說,你找到了fiddle這裏。

+1

有人能解釋下投票? –

0

我會做這樣的事

$('#img_id').click(function(){ 
    $("#wrapper").html('<img src="' + $(this).attr)('data-url') + '?' + new Date().getTime() + '">'); 
}); 
相關問題