2013-01-17 61 views
2

在每一頁加載我正在更改圖像。我發現這個插件做的很好。每次頁面加載時拉出一個隨機圖像

(function($){ 

    $.randomImage = { 
     defaults: { 

      //you can change these defaults to your own preferences. 
      path: '/templates/default/images/', //change this to the path of your images 
      myImages: ['fab_ad1.jpg', 'fab_ad2.jpg', 'fab_ad3.jpg'] //put image names in this bracket. ex: 'harold.jpg', 'maude.jpg', 'etc' 

     }   
    } 

    $.fn.extend({ 
      randomImage:function(config) { 

       var config = $.extend({}, $.randomImage.defaults, config); 

       return this.each(function() { 

         var imageNames = config.myImages; 

         //get size of array, randomize a number from this 
         // use this number as the array index 

         var imageNamesSize = imageNames.length; 

         var lotteryNumber = Math.floor(Math.random()*imageNamesSize); 

         var winnerImage = imageNames[lotteryNumber]; 

         var fullPath = config.path + winnerImage; 


         //put this image into DOM at class of randomImage 
         // alt tag will be image filename. 
         $(this).attr({ 
             src: fullPath, 
             alt: winnerImage 
            }); 


       }); 
      } 

    }); 



})(jQuery); 

HTML:

<img class="shuffle" src="" alt="" onclick="chooseLink()"> 

調用此函數:

$('.shuffle').randomImage(); 

使用此功能,我在我的網頁上顯示廣告。我爲每個廣告圖片分開鏈接。當一個圖像被點擊時,我打電話給一個javascript函數,在那裏我需要識別圖像名稱,並相對於我重定向到單獨的鏈接。在我的情況下,我不知道如何識別被點擊的圖像名稱。請告訴我如何識別被點擊的圖片名稱。
希望我的問題清楚。 在此先感謝!

+0

不能用onClick事件添加特定ID來描述圖像嗎? – Peon

+0

**我需要識別圖像名稱**你可以試試看嗎? – Jai

回答

2

變化

<img class="shuffle" src="" alt="" onclick="chooseLink()"> 

<img class="shuffle" src=""> 

並把這個在你的腳本:

$('.shuffle').click(function(){ 
    var imageId = this.src.split('/').pop(); // this is the name of your image file 
              // It identifies the image 
    // use the image 
    chooseLink(imageId); 
}); 
+0

+1 Thankyou @dystroy it Works good ... –

0

你可以修改你的形象HTML點點:

<img class="shuffle" src="" alt=""> 

然後補充說明

$('.shuffle').randomImage().click(function(){ 
    var imgsrc = $('.shuffle').attr('src'); 
    var imgname = imgsrc.substr(imgsrc.lastIndexOf('/')+1); 
    chooseLink(imgname); 
}); 
相關問題