通常情况下,写了一个插件,最好的约定是这样的:
$.fn.pluginName = function(){
// return the same object to preserve chainability
// and also apply the plugin's functionality to all the
// dom elements in this jquery collection
return this.each(function(i,el){
// do whatever you want with $(el)
});
};
如果你正在写返回,而不是在某种程度上当前对象(比如像width
作品操纵值插件),你应该返回值,而不是当前对象的引用(this
):
$.fn.maxWidth = function(){
var max = 0;
this.each(function(i,el){
var w = $(el).width();
if(w > max)
max = w;
});
return max;
};
如果你想给用户访问&修改的可能性哟你应该保持链接性(我的意思是返回this
而不是包含你插件的api的其他对象),并通过jQuery元素的data
方法向用户公开插件的API。
下面是一个例子。让我们说我们正在制作一个视频播放器jquery插件。我们希望保持链接性,但仍然能够访问此插件的核心功能。
做到这一点的正确的方式将是这样的:
$.fn.videoPlayer = function(){
var api = {
play : function(){/*...*/},
pause : function(){/*...*/},
stop : function(){/*...*/}
};
return this.each(function(i,el){
$(el).data('videoPlayerApi',api);
});
};
的使用示例这表明我的观点:
$('video')
// initialising the plugin
.videoPlayer()
// the return value is the original jQuery object,
// so we can still call jQuery methods on it
.css('opacity',1)
// select the first video
.eq(0)
// access the first video's plugin api
.data('videoPlayerApi')
// start only the first video
.start();