编写jquery插件
本文讲下开发jquery插件必须应有的要求。
1、在JQuery命名空间下声明只声明一个单独的名称
2、接受options参数,以便控制插件的行为
3、暴露插件的默认设置 ,以便外面可以访问
4、适当地将子函数提供给外部访问调用
5、保持私有函数
6、支持元数据插件
那么下文一一来解析。
只声明一个单独的名称
这表明是一个单独的插件脚本。如果你的脚本包含多个插件或者是互补的插件(像$.fn.doSomething()和$.undoSomething()),那么你可以根据要求声明多个名称。但一般情况下,力争用单一的名称来维持插件现实的所有细节。
在本例中,我们将声明一个叫“hilight”的名称
// 插件的定义$.fn.hilight = function( options ){ // 这里就是插件的实现代码了... };
然后我们可以像这样调用它:
$("divTest").hilight();
接受一个options参数,以便控件插件的行为
这里值得注意的是$.extend()第一个参数是一个空的对象,这样可以让我们重写插件的默认设置
用户可以像这样使用插件:
)。例如,我们在插件里声明了一个函数叫“format”用来高这显示文本,我们的插件实现代码可能是这样子的:////create closure//(function($){ // // plugin definition // $.fn.hilight = function(options){ debug(this); //build main options before element iteration var opts = $.extend({}, $.fn.hilight.defaults, options); //iterate and reformat each matched element return this.each(function(){ $this = $(this); //build element specific options var o = $.meta ? $.extend({}, opts, $this.data()) : opts; //update element styles $this.css({ backgroundColor: o.background, color: o.foreground }); var markup = $this.html(); //call our format function }); } // // private function for debugging // function debug($obj){ if(window.console && window.console.log){ window.console.log('hilight selection count: ' $obj.size()); } }; // // define and expose our format function // $.fn.hilight.format = function(txt){ return '<strong>' txt '</strong>'; }; // // plugin defaults // $.fn.hilight.defaults = { foreground : 'red', background : 'yellow' }; // // end of clousure //})(jQuery);