Share study notes for the jQuery plugin

  • 2020-12-07 03:57:13
  • OfStack

A plug-in (Plugin), also known as an jQuery extension (Extension), is a program written using an application programming interface (API) that conforms to specification 1. There are now over thousands of jQuery plug-ins, written, validated, and perfected by developers from around the world. For jQuery developers, direct use of these plug-ins will quickly stabilize the architecture system and save project costs.

1. Summary of the plugin

Based on the core code of jQuery, the plug-in writes a composite 1 specification application program. In other words, the plug-in is also jQuery code, which can be embedded in the way that the js file was introduced.

There are many types of plug-ins, which can be roughly divided into UI class, form and validation class, input class, effects class, Ajax class, sliding class, graphic image class, navigation class, integrated tools class, animation class, and so on.

The introduction of plug-ins requires 1 specific step, which is basically as follows:

1. The jquery. js file must be introduced first and before all plug-ins; 2. Introduce plug-ins; 3. Introduce the periphery of the plug-in, such as skin, Chinese bag, etc.

Such as to the most common form of authentication plug-in: validate, in addition to the most basic plugin file jquery. validate. min. js, with messages_zh. js and so on national language pack can be used for you.

How to use this plug-in is not described here, you can check out the video jQuery on MOOC - Validation Plugin, which describes the various configuration items and extensions of this plug-in in detail.

By analogy, a good plug-in, detailed documentation is essential, detailed documentation can see, and in the local test can let you quickly get started with the use of various plug-ins.

There are also various plug-ins written by others that you can use, such as the plug-ins for managing cookie, cookie, and so on.

Plug-ins can go to jQuery official website of the plug-in module for The jQuery Plugin Registry

2. Custom plug-ins

Previously we used a good plug-in provided by others, it is very convenient to use. If the market can not find their own satisfactory plug-in, and want to encapsulate a plug-in for others to use. Then you need to write your own jQuery plug-in.

1. Types of plug-ins

According to functional classification, the forms of plug-ins can be divided into 1 and 3 categories:

Plug-ins that encapsulate object methods; (That is, jQuery object based on an DOM element, local, most used) Plugins that encapsulate global functions; (Global encapsulation) Selector plug-in. (similar to.find (), for example: color(red) to select all red elements, etc.)

2. Basic points of plug-ins

It is mainly used to solve various conflicts, errors and other problems caused by plug-ins, including the following:

It is recommended to use jQuery.[plug-in name].js to avoid conflicts with other js files or other libraries (alert($.[plug-in name]) can be used to verify the existence of this global method); Local object attached to jQuery. fn object, global function attached to jQuery object itself (you can use alert($(selector).[plug-in name]) to verify the existence of the local method); Inside the plug-in, this points to the current local object (the jQuery object obtained through the selector); All elements can be traversed by this.each; All methods or plug-ins must be ended with a semicolon to avoid problems (a semicolon can be added to the header of the plug-in to make it safer); The plug-in should return the jQuery object to ensure the chain operation; Avoid using $internally in the plug-in. If you do, use the closure to pass jQuery in, so that $continues to be used internally as the alias for jQuery.

;(function($){// There will be $ As a parameter of an anonymous function 
/* Write the code here and use it $ As a jQuery Abbreviation alias */
})(jQuery);// There will be jQuery Passed as arguments to anonymous functions 

3. Write a plug-in

Suppose our plug-in requirement is to implement a drop-down menu, display the corresponding drop-down list when moving in the element, and withdraw it when moving out. And you can set the text color when it expands.

By convention, we can constrain the html structure when writing plug-ins. Now suppose we have the following HTML structure on our page:


<ul class="list">
 <li> Navigation lists 1
  <ul class="nav">
   <li> Navigation lists 1</li>
   <li> Navigation lists 2</li>
   <li> Navigation lists 3</li>
   <li> Navigation lists 4</li>
   <li> Navigation lists 5</li>
   <li> Navigation lists 6</li>
  </ul>
 </li>
 <li> Navigation lists 2
  <ul class="nav">
   <li> Navigation lists 1</li>
   <li> Navigation lists 2</li>
   <li> Navigation lists 3</li>
   <li> Navigation lists 4</li>
   <li> Navigation lists 5</li>
   <li> Navigation lists 6</li>
  </ul>
 </li>
</ul>
<!--  Default has been introduced jquery -->

At this point, we have the first requirement for our plug-in implementation that the ul list must be created under the elements that require hover representation, and that className be nav. (The plugin is internally based on this condition)

Now you're ready to write our plug-in. Save as ES103en. nav. js, (meets the above requirements, imported by default)


;(function($){
 $.extend({ // Plug-ins are defined on global methods 
  "nav" : function (color){// Pass in the parameters, this is just a tidbit, as you write, the parameter options can be much richer, such as pass in json Objects, etc. 
   $('.nav').css({// Style the expanded drop-down list, detailed here below 
    "list-style" : "none",
    "margin" : 0,
    "padding" : 0,
    "display" : "none",
    "color":color// Controlled by users hover ", displays the text color of the list 
   });
   $('.nav').parent().hover(// It's used here .nav Is the parent node of hover Elements to) 
    // Because we can only set it within the bounds of what the plug-in requires, using an external selector is a violation of this principle 
    function (){
     $(this).find(".nav").stop().slideDown("normal");// Notice we're using it here jquery Method of animation 
    },function (){
     $(this).find(".nav").stop().slideUp("normal");// Pay attention to stop() Otherwise it would have an accordion effect, but that's not what we need 
    });
  }
 });
})(jQuery);

Note: The css method is used here just for convenience. In real plug-in writing, when such a large number of css styles exist, it is recommended to define the css style externally, for example by rewriting it as:

The plug-in relies on css, which needs to be imported into html from plug-in 1


.hover{/* Plug-in must style */
 list-style: none;
 margin:0;
 padding: 0;
 display: none;
}

Modify within the plug-in.


$('.nav').addClass("hover");// will CSS with jQuery Separation of 
$('.nav').css("color",color);// Enabled when user Settings exist, not when they don't exist (to judge) 

This is the js file for the plug-in. Finally, to be effective, don't forget to add the following sentence to the js page (the plug-in is currently defined on the global method)


$(function (){
 $.nav("#999");// Call the global method implemented by the plug-in and set its render background color to #999 . 
});

So, our global plug-in is written, and the call is complete. Refresh your page to see if it has an effect.

However, because our methods are defined globally, there is now an hover rendering whenever the structure specified by our plug-in appears on the page, but sometimes we don't want it to be, we want it to be called locally, within the element I specify. Therefore, we need to make some modifications to make it a local method, which is also very simple:


;(function($){
 $.fn.extend({// Is defined as a local method 
  "nav" : function (color){
   $(this).find('.nav').addClass('hover');// I've already said that , At this time this Points to the element that called the method 
   $(this).find('.nav').css("color",color);// Under the current element, added 1 time find Filter, which is implemented in the corresponding element. 
   $(this).find('.nav').parent().hover(
    function (){
     $(this).find(".nav").stop().slideDown("normal");
    },function (){
     $(this).find(".nav").stop().slideUp("normal");
    });
   return this;// Returns the current object 
  }
 });
})(jQuery);

Let's go ahead and refresh 1 browser. And you're like, gee, why isn't it working? Of course, because the original code is called directly from the global, now become a local method, obviously can not do this, need to make 1 change:

I won't post the html code here, but I hope you'll make a few copies of the above html code in practice to think about its implementation


$(function (){// Here, eq(0) Student: It's only for the 1 Copy has effect, copy has no effect. 
 // You can take the top one find Try again after filtering and deleting, and you will see that it works on the remaining copies.) 
 $(".list").eq(0).nav("red");// Calling local methods 
});

Now let's go back to the plug-in code we wrote that corresponds to the points we wrote above, and think about what we haven't done yet. And you'll see that you're almost there. We now have a drop-down menu of plugins.

In fact, it is not difficult to write a plug-in, the most important thing is that when we write a plug-in, 1 must always pay attention to such a point, every detail follows the best implementation summarized in the process of practice, in order to customize the implementation of a good plug-in.

Code is written first for individuals and then for machines.


Related articles: