编写Jquery的plugin

来源:互联网 发布:手游麻将源码架设教程 编辑:程序博客网 时间:2024/06/06 03:36

源地址:http://justcoding.iteye.com/blog/728455


如何写一个Jquery 的Plugin插件

    博客分类: 
  • Javascript /Jquery / Bootstrap / Web
jQuery配置管理脚本FirebugJavaScript 

JQuery Plugin插件,如果大家不明白什么是JQuery插件或都不清楚如何编写可以查看其官方的网站:jQuery Authoring Guidelines

 

好了,下面有一些我觉得想做一个好的插件必须应有的要求:

1、在JQuery命名空间下声明只声明一个单独的名称

2、接受options参数,以便控制插件的行为

3、暴露插件的默认设置 ,以便外面可以访问

4、适当地将子函数提供给外部访问调用

5、保持私有函数

6、支持元数据插件

 

下面将逐条地过一遍:

只声明一个单独的名称

这表明是一个单独的插件脚本。如果你的脚本包含多个插件或者是互补的插件(像$.fn.doSomething()和$.undoSomething()),那么你可以根据要求声明多个名称。但一般情况下,力争用单一的名称来维持插件现实的所有细节。

在本例中,我们将声明一个叫“hilight”的名称

 

Js代码  收藏代码
  1. // 插件的定义  
  2. $.fn.hilight = function( options ){  
  3.     // 这里就是插件的实现代码了...  
  4.       
  5. };  
 

然后我们可以像这样调用它:

 

Js代码  收藏代码
  1. $("divTest").hilight();  
 

 

 

接受一个options参数,以便控件插件的行为

Js代码  收藏代码
  1. $.fn.hilight = function(options){  
  2.     var defaults = {  
  3.         foreground    :    'red',  
  4.         background    :    'yellow'  
  5.     };  
  6.     //Extends out defaults options with those privided 扩展我们默认的设置  
  7.     $.extend(defaults,options);  
  8. };  
 

而我们可以这样使用它:

 

Js代码  收藏代码
  1. $('#myDiv').hilight({  
  2.   foreground: 'blue'  
  3. });  
 

 

暴露插件的默认设置 ,以便外面可以访问

作为插件的提升和优化,我们应该将上面的代码暴露出来作为插件的默认设置。

这非常重要,这样做让使用插件的用户可以非常容易地用最少的代码重写或自定义该插件。然而这个我们可以借助JavaScript function对象的优势:

 

Js代码  收藏代码
  1. $.fn.hilight = function(options){  
  2.     //Extend our default options with those provided  
  3.     //Note that the first arg to extend is an empty object  
  4.     //this is to keep from overriding our "defaults" object  
  5.     var opts = $.extend({},$.fn.hilight.defaults,options);  
  6. }  
  7. $.fn.hilight.defaults = {  
  8.     foreground    :    'red',  
  9.     background    :    'yellow'  
  10. };  
 

这里值得注意的是$.extend()第一个参数是一个空的对象,这样可以让我们重写插件的默认设置

用户可以像这样使用插件:

 

Js代码  收藏代码
  1. // override plugin default foreground color  
  2. $.fn.hilight.defaults.foreground = 'blue';  
  3. // ...  
  4. // invoke plugin using new defaults  
  5. $('.hilightDiv').hilight();  
  6. // ...  
  7. // override default by passing options to plugin method  
  8. $('#green').hilight({  
  9.   foreground: 'green'  
  10. });  
 

适当地将子函数提供给外部访问调用

这个例子延续前面的例子,你会发现有一个有趣的方法可以扩展你的插件(然后还可以让其他人扩展你的插件 :))。例如,我们在插件里声明了一个函数叫“format”用来高这显示文本,我们的插件实现代码可能是这样子的:

 

Js代码  收藏代码
  1. $.fn.hight = function(options){  
  2.     //iterate and reformat each mached element  
  3.     return this.each(function(){  
  4.         var $this = $(this);  
  5.         //...  
  6.         var markup = $this.html();  
  7.         //call our format function  
  8.         markup = $.fn.hilight.format(markup);  
  9.         $this.html(markup);  
  10.     });  
  11. };  
  12. //define our format function  
  13. $.fn.hilight.format = function(txt){  
  14.     return '<strong>' + txt + '</strong>';  
  15. };  
 

 

保持私有函数

暴露插件有部分内容提供重写看上去似乎非常强大,但是你必须认真地考虑你的插件哪一部分是需要暴露出来的。一旦暴露出来,你就需要考虑这些变化点,一般情况下,如果你没有把握哪部分需要暴露出来,那么你可以不这样做。

那如何才能够定义更多的函数而不将其暴露出来呢?这个任务就交给闭包吧。为了证实,我们在插件中添加一个函数叫“debug”,这debug函数将会记录已选择的元素数量到FireBug控制台中。为了创建闭包,我们将插件定义的整部分都包装起来:

 

Js代码  收藏代码
  1. //create closure  
  2. (function($){  
  3.     //plugin definition  
  4.     $.fn.hilight = function(options){  
  5.         debug(this);  
  6.         //...  
  7.     };  
  8.     //private function for debuggin  
  9.     function debug($obj){  
  10.         if(window.console && window.console.log){  
  11.             window.console.log('hilight selection count :' + $obj.size());  
  12.         }  
  13.     }  
  14.     //...  
  15.     //end of closure  
  16. })(jQuery);  
 

 

这样“debug”方法就不能被闭包这外调用了

 

支持元数据插件

 

依赖于所写的插件类型,并支持元数据插件会使得其本身更加强大。个人来讲,我喜欢元素据插件,因为它能让你分离标签中重写插件的配置 (这在写demo和示例时特别有用)。最重要的是,想现实它特别的容易!

 

 

Js代码  收藏代码
  1. $.fn.hilight = function(options){  
  2.     //build main options before element interation  
  3.     var opts = $.extend({},$.fn.hilight.defaults,options);  
  4.     return this.each(function(){  
  5.         var $this = $(this);  
  6.         //build element specific options  
  7.         var o = $.meta ? $.extend({},opts,$this.data()) : opts;  
  8.   
  9.          //一般句话,搞定支持元数据 功能         
  10.     });  
  11. }  
 

几行的变化完成了以下几件事:

1、检测元数据是否已经配置

2、如果已配置,将配置属性与额外的元数据进行扩展

 

Html代码  收藏代码
  1. <!--  markup  -->  
  2. <div class="hilight { background: 'red', foreground: 'white' }">  
  3.   Have a nice day!这是元数据  
  4. </div>  
  5. <div class="hilight { foreground: 'orange' }">  
  6.   Have a nice day!在标签中配置  
  7. </div>  
  8. <div class="hilight { background: 'green' }">  
  9.   Have a nice day!  
  10. </div>  
 

然后我们通过一句脚本就可以根据元数据配置分开地高亮显示这些div标签:

 

 

Js代码  收藏代码
  1. $('.hilight').hilight();  
 

最后,将全部代码放在一起:

 

Js代码  收藏代码
  1. //  
  2. //create closure  
  3. //  
  4. (function($){  
  5.     //  
  6.     // plugin definition  
  7.     //  
  8.     $.fn.hilight = function(options){  
  9.         debug(this);  
  10.         //build main options before element iteration  
  11.         var opts = $.extend({}, $.fn.hilight.defaults, options);  
  12.         //iterate and reformat each matched element  
  13.         return this.each(function(){  
  14.             $this = $(this);  
  15.             //build element specific options  
  16.             var o = $.meta ? $.extend({}, opts, $this.data()) : opts;  
  17.             //update element styles  
  18.             $this.css({  
  19.                 backgroundColor: o.background,  
  20.                 color: o.foreground  
  21.             });  
  22.             var markup = $this.html();  
  23.         //call our format function  
  24.           
  25.         });  
  26.     }  
  27.       
  28.     //  
  29.     // private function for debugging  
  30.     //  
  31.     function debug($obj){  
  32.         if(window.console && window.console.log){  
  33.             window.console.log('hilight selection count: ' + $obj.size());  
  34.         }  
  35.     };  
  36.     //  
  37.     // define and expose our format function  
  38.     //  
  39.     $.fn.hilight.format = function(txt){  
  40.         return '<strong>' + txt + '</strong>';  
  41.     };  
  42.       
  43.     //  
  44.     // plugin defaults  
  45.     //  
  46.     $.fn.hilight.defaults = {  
  47.         foreground    :    'red',  
  48.         background    :    'yellow'  
  49.     };  
  50.       
  51.     //  
  52.     // end of clousure  
  53.     //  
  54. })(jQuery);  
 

 

 

 

2.

如何写一个Jquery 的Plugin插件

 

最近做项目想要一个控制会计数字输入的jquery插件,找了好久找不到, 没用办法,只有自己操刀上阵了,其实要求也不高, 就是: 
1. 默认是: 0.00 
2. 只能输入数字和小数点, 其它输入将被忽略 
3. 输入整数后继续自动保持两位小数 
4. 可以定义自己想保留几位小数

 

 

OK, 开始动手:

首先, 通过将函数封装为jquery plugin包, 可以将这个包非常容易的在各种项目和页面中使用, 而且代码管理维护起来方便. 再说, jquery的plugin实现起来超简单,为什么不这么做呢?如果你是第一次开发, 先阅读下这篇文章吧: How jQuery Works

 

一. Jquery Plugin 的基本框架

 

Js代码  收藏代码
  1. (function($) {  
  2.     $.fn.extend({  
  3.         MyPlugin: function(options) {  
  4.             var defaults = {  
  5.                 decimal_length: 2,  
  6.             };  
  7.             var options = $.extend(defaults, options);  
  8.             var len = parseInt(options['decimal_length']);  
  9.             return this.each(function() {  
  10.                 alert('edison');  
  11.             });  
  12.         }  
  13.     });  
  14. })(jQuery);  
 

其中options就是参数, 调用方法为:

 

Js代码  收藏代码
  1. $('#ddd').MyPlugin({decimal_length:2});  

 

好的, 我们接着完成要的功能: 文件名为 money.js

 

Js代码  收藏代码
  1. (function($) {  
  2.     var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask";  
  3.     $.fn.extend({  
  4.         money_type: function(options) {  
  5.             var defaults = {  
  6.                 decimal_length: 2,  
  7.             };  
  8.             var options = $.extend(defaults, options);  
  9.             var len = parseInt(options['decimal_length']);  
  10.             return this.each(function() {  
  11.                 var input = $(this);  
  12.   
  13.                 function caret() {  
  14.                     var input_value = input.val();  
  15.                     var reCat = /\d+\.?\d{0,2}/i;  
  16.                     var_new_value = reCat.exec(input_value);  
  17.                     input.val(var_new_value);  
  18.                 }  
  19.   
  20.                 input.bind("click"function(e) {  
  21.                     if (input.val() == '0.00') {  
  22.                         input.select();  
  23.                     }  
  24.                 })  
  25.                 .bind(pasteEventName, function() {  
  26.                     setTimeout(caret, 0);  
  27.                 });  
  28.             });  
  29.         }  
  30.     });  
  31. })(jQuery);  
 

 

OK, 插件完成, 在使用的时候要包含这个文件和jquery文件, 然后通过以下代码就可以调用了

 

 

Js代码  收藏代码
  1. $('#ddd').money_type();// 默认保留两位小数  
 

0 0
原创粉丝点击