How to write a jQuery plugin

Original Link: http://www.cnblogs.com/leekenky/p/4088843.html

JQuery Plugin plug-ins, if you don't know what a JQuery plug-in is or how to write a website where you can view it officially: jQuery Authoring Guidelines

 

Okay, here are some requirements that I feel I must have in order to be a good plugin:

1. Declare only a single name in the JQuery namespace

2. Accept options parameters to control plug-in behavior

3. Expose the default settings of the plug-in so that it can be accessed outside

4. Provide subfunctions appropriately to external access calls

5. Keep Private Functions

6. Support metadata plug-in

 

The following will be done one by one:

Declare only a single name

This indicates a separate plug-in script.If your script contains multiple or complementary plug-ins (such as $.fn.doSomething() and $.undoSomething()), you can declare multiple names as required.Typically, however, a single name is strived to maintain all the details of the plug-in's reality.

In this case, we'll declare a name called "hilight"

 

  1. //Definition of plug-ins
  2. $.fn.hilight = function( options ){  
  3.     //Here's the implementation code for the plug-in...
  4.       
  5. };  
 

Then we can call it like this:

 

  1. $("divTest").hilight();  
 

 

 

Accept an option parameter to control the behavior of the plug-in

  1. $.fn.hilight = function(options){  
  2.     var defaults = {  
  3.         foreground    :    'red',  
  4.         background    :    'yellow'  
  5.     };  
  6.     //Extends out defaults options with those privided Extend our default settings
  7.     $.extend(defaults,options);  
  8. };  
 

And we can use it like this:

 

  1. $('#myDiv').hilight({  
  2.   foreground: 'blue'  
  3. });  
 

 

Expose the plug-in's default settings so they are accessible outside

As a promotion and optimization of plug-ins, we should expose the code above as the default settings for plug-ins.

This is important so that users of the plug-in can easily rewrite or customize it with minimal code.However, we can take advantage of the JavaScript function object:

 

  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. };  
 

It is worth noting here that the first parameter of $.extend() is an empty object, which allows us to override the plug-in's default settings

Users can use plug-ins like this:

 

  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. });  
 

Provide subfunctions appropriately to external access calls

Continuing with the previous example, you will find an interesting way to extend your plug-in (and then let others extend your plug-in:).For example, we have declared a function called "format" in our plug-in to highlight this display text. Our plug-in implementation code might look like this:

 

  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. };  
 

 

Keep Private Functions

Exposing parts of your plug-in to provide overrides may seem very powerful, but you must carefully consider which parts of your plug-in need to be exposed.Once exposed, you need to consider these points of change, and in general, if you're not sure which parts need to be exposed, you can avoid doing so.

So how can you define more functions without exposing them?Leave the task to the closure.To verify, we add a function called "debug" to the plug-in that will record the number of elements selected to the FireBug console.To create a closure, we wrap the entire definition of the plug-in:

 

  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);  
 

 

This way the "debug" method cannot be called outside of the closure

 

Supports metadata plug-ins

 

Depending on the type of plug-in you write, and supporting metadata plug-ins makes them more powerful.Personally, I like element data plugins because they allow you to separate tags and override their configuration (which is especially useful when writing demo s and examples).Most importantly, it's especially easy to think about it!

 

 

  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.          //In general, develop metadata support capabilities.
  10.     });  
  11. }  
 

A few line changes accomplish the following things:

1. Detect if metadata is configured

2. Extend configuration properties with additional metadata if configured

 

  1. <!--  markup  -->  
  2. <div class="hilight { background: 'red', foreground: 'white' }">  
  3.   Have a nice day!This is metadata  
  4. </div>  
  5. <div class="hilight { foreground: 'orange' }">  
  6.   Have a nice day!Configure in Tags  
  7. </div>  
  8. <div class="hilight { background: 'green' }">  
  9.   Have a nice day!  
  10. </div>  
 

Then we can highlight these div tags separately according to the metadata configuration with a script:

 

 

  1. $('.hilight').hilight();  
 

Finally, put all the code together:

 

  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.

How to write a Plugin plugin for Jquery

 

Recent projects want a jquery plug-in to control accounting number input, found for a long time can not find, no way to do it, only their own knife in battle, in fact, the requirements are not high, that is:
1. Default: 0.00
2. Only numbers and decimal points can be entered, other inputs will be ignored.
3. Keep two decimal places automatically after entering an integer
4. You can define how many decimal places you want to keep

 

 

OK, get started:

First, by encapsulating a function as a jquery plugin package, you can easily use this package in a variety of projects and pages, and code management is easy to maintain. Also, jquery's plugin implementation is very simple, so why not? If you're new to development, read this article first: How jQuery Works

 

1. Basic framework of Jquery Plugin

 

  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);  
 

Where options is the parameter and is called by:

 

  1. $('#ddd').MyPlugin({decimal_length:2});  

 

Okay, let's go ahead and do what we need: the file name is money.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, plug-in complete, include this file and jquery file when using it, then call it with the following code

 

 

  1. $('#ddd').money_type();//Keep two decimal places by default
 

Reprinted at: https://www.cnblogs.com/leekenky/p/4088843.html

Keywords: JQuery Javascript

Added by twilliamson on Mon, 22 Jul 2019 23:50:08 +0300