2011-11-29 72 views
0

我想要點擊一個拇指來顯示一個更大的圖像與預加載程序,然後在加載完成時淡入。jquery更改圖像源取決於div點擊的ID

我幾乎沒有感謝this answer - 這使得不同的圖像取決於被點擊什麼拇指加載 - 和this guide其中挑選出的裝載位。

結合使用這兩種我有以下腳本:

<script type="text/javascript"> 
    <!-- 
    $(function() { 
     $('img[id^="thumb"]').click(function() { 
     $('#loader').show(); 
     var id = $(this).attr('id').replace('thumb', ''); 
     var img = new Image(); 
     $(img).load(function() { 
      //$(this).css('display', 'none'); 
      $(this).hide(); 
      $('#loader').removeClass('loading').append(this); 
      $(this).fadeIn(); 
     }).attr('src', 'photos/1.jpg'); 
    }); }); 

    //--> 
    </script> 

您將在該.attr源固定一個圖像上月底通知。我想要的是,'.jpg'之前的數字取決於拇指的標識(它們被標記爲:'thumb1','thumb2'等)。

有沒有這樣做的方法?非常感謝!

ps This answer似乎是接近,但我的問題是,拇指ID似乎爲時過早,可以使用這種簡單的解決方案。

+0

我建議你看看的Javascript閉包,這將清除約你的困惑「拇指ID似乎過於早在腳本能夠使用這種簡單的解決方案」 –

回答

2
<script type="text/javascript"> 

    $(function() { 
     $('img[id^="thumb"]').click(function() { 
     var thumbId = $(this).attr('id').substring(5); // assuming the id of the thumb is like "thumb1", "thumb2", ... 
     $('#loader').show(); 
     var id = $(this).attr('id').replace('thumb', ''); 
     var img = new Image(); 
     $(img).load(function() { 
      //$(this).css('display', 'none'); 
      $(this).hide(); 
      $('#loader').removeClass('loading').append(this); 
      $(this).fadeIn(); 
     }).attr('src', 'photos/' + thumbId + '.jpg'); 
    }); }); 


    </script> 
+0

賓果!多謝,夥計。 – bravokiloecho

+0

不要忘記接受答案:) –