2014-01-07 34 views
-1

我正在做我自己的畫廊腳本,但是當我嘗試和alert(this)它返回[對象對象]。自定義jQuery插件返回[對象對象]

我這樣調用

$('#images').createGallery({ 
    server: 'http://localhost/jQuery%20Gallery/images/galleries/', 
    galleryName: 'Test', 
    galleryWidth: 800, 
    galleryImageMargin: 20, 
    galleryImageColumns: 2, 
    galleryTargetFolder: 'homepage_gallery', 
    imageQuality: 100 
}); 

和我的函數的代碼我的功能是這樣的:

(function ($) { 
    $.fn.createGallery = function(options) { 
     alert(this); 
     var settings = $.extend({ 
      // These are the defaults. 
      server: 'http://localhost/jQuery%20Gallery/images/galleries/', 
      galleryName: 'Test', 
      galleryWidth: 800, 
      galleryImageMargin: 20, 
      galleryImageColumns: 2, 
      galleryTargetFolder: 'homepage_gallery', 
      imageQuality: 100 
     }, options); 

     var galleryImageWidth = settings.galleryWidth/settings.galleryImageColumns; 
     var imageUrl = settings.server+settings.galleryTargetFolder; 

     var otherMargin = Math.round(settings.galleryImageMargin/2); 
     var finalImageWidth = Math.round(galleryImageWidth - settings.galleryImageMargin); 
     var finalImageHeight = Math.round(galleryImageWidth/1.4); 
     var finalGalleryWidth = settings.galleryWidth - settings.galleryImageMargin; 

     $('#'+this).before('<style>#'+this+' li:nth-child('+settings.galleryImageColumns+'n+1) { margin-left: 0; } #'+this+' li:first-child { margin-left: 0; } #'+this+' { width: '+finalGalleryWidth+'px; margin: 0px; } #'+this+' li { display: inline-block; list-style: none; margin-left: '+settings.galleryImageMargin+'px; margin-bottom: '+otherMargin+'px; } </style>'); 

     $.ajax({ 
      url: imageUrl, 
      success: function(data){ 
       $(data).find("a:contains(.jpg)").each(function(){ 
        // will loop through 
        var filename = $(this).attr("href"); 
        $('<li></li>').html('<img src="thumbnail.php?src='+imageUrl+'/'+filename+'&q='+imageQuality+'&h='+finalImageHeight+'&w='+finalImageWidth+'"/>').appendTo('#'+$(this)); 
       }); 
      } 
     }); 
    }; 
}(jQuery)); 
+2

「console.log(this)」怎麼辦? alert()方法只能處理字符串。順便說一句,在調試目的中使用alert()並不推薦,因爲模態行爲 –

+0

你認爲'this'是什麼? – charlietfl

回答

4

這是完全正確的,因爲this指托特他的jQuery包裝對象,其默認字符串實現提供[object Object]

如果要查看this的值是什麼console.log(this) - 這是利用了瀏覽器的開發者工具

提供的控制檯

演示:Fiddle

注:也不要忘了從插件返回this保持chainability。

+0

啊,謝謝。我已經按照你的說法完成了,並且該對象在[ul#images]中出現。我如何使用圖像作爲圖庫的目標ID? –

+1

@AndyHolmes這個問題與你的開場白無關,請考慮接受這個答案並提出一個新問題 –

+1

好的,稍後會做 –