我正在写这个自定义函数:
(function ($) {
$.fn.createGallery = function(options) {
//alert(this);
console.log(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));
使用以下行调用:
$('#images').createGallery({
server: 'http://localhost/jQuery%20Gallery/images/galleries/',
galleryName: 'Test',
galleryWidth: 800,
galleryImageMargin: 20,
galleryImageColumns: 2,
galleryTargetFolder: 'homepage_gallery',
imageQuality: 100
});
console.log(this)
返回ul#images
。正如您在我的代码中所看到的,我尝试调用this
来反映已找到的ID。但是,在代码中它返回[object Object]
。我如何使用this
来反映我正在应用我的函数的对象?
答案 0 :(得分:1)
使用$(this).attr("id")
代替(您应该使用其他值缓存。)在您的函数中,this
引用HTML元素。
答案 1 :(得分:1)
使用$(this).selector
代替“this”
“selector”是jQuery-Objects的一个属性,它以String-format返回选择器。
因此你的行:
$(this).before('<style>'+this+' li:nth-child [...]
应该成为:
$(this).before('<style>'+$(this).selector+' li:nth-child [...]