我正在创建自己的图库脚本,但是当我尝试alert(this)
时,它会返回[object Object]。
我这样称呼我的功能
$('#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));
答案 0 :(得分:4)
这是完全正确的,因为this
指的是jQuery包装器对象,其默认为字符串实现提供[object Object]
如果您想查看this
使用console.log(this)
的价值是什么 - 这会使用浏览器开发人员工具提供的控制台
演示:Fiddle
注意:另外,请不要忘记从插件返回this
以保持可链接性。