通常情況下,寫了一個插件,最好的約定是這樣的:
$.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();