occasionally , You want to have a function that can be used throughout the code . for example , You may want to have a single way to jQuery On the selector , Used to handle a series of operations on the selector . Or maybe you've written a very useful tool function , And hope to be able to simply migrate to other projects . under these circumstances , You may want to write a plug-in .

jQuery working principle 101:jQuery Object method and tool method

Before we write plug-ins , The first thing we need to do is jQuery I have some understanding of how . Take a look at this code :

 $( "a" ).css( "color", "red" );

This is a fairly basic jQuery Code , But do you know what's going on behind the scenes ? Whenever you use that $ Method to select an element , It returns a jQuery object . This object contains all the methods you've used (.css(), .click(), etc.) And all the elements that match the selector .jQuery Objects from $.fn Object to get these methods . This object contains all jQuery Object method , And if we want to write our own methods , It will also include these methods .

Besides ,jQuery Tool method $.trim() It is used to remove any leading or trailing white space characters from the user's input . Tool methods are those that reside directly in $ The method itself . When you expand jQuery API You don't have to worry about what you get back DOM When elements operate , You may want to write a tool method plug-in .

( The main idea of the original text is that $.trim() Method , And then explain it , But there's nothing on it $.trim(), So I have to do this .)

Basic plug-in writing

For example, we want to create a plug-in , Used to turn text in a set of retrieved elements green . All we need to do is add one called greenify The way to $.fn among , After that you will be able to use other jQuery Using it like the object method .

 $.fn.greenify = function() {
this.css( "color", "green" );
}; $( "a" ).greenify(); // Makes all the links green.

It should be noted that , Using another method .css() when , We used this instead of $(this) . It's because of our greenify Methods and .css() Belong to the same object .


The plug-in is ready to use , But we want our plug-in to be used in real combat , There are a few things we need to do . The serial is jQuery One of the characteristics of , It allows you to connect five or more operations on one selector . It's all done by putting all the jQuery Object method returns to the original jQuery Object ( But there are some exceptions : Call... Without parameters .width() Method returns the width of the selected element , And it can't be connected ). Let's use one line of code to make our plug-in method concatenate :

 $.fn.greenify = function() {
this.css( "color", "green" );
return this;
} $( "a" ).greenify().addClass( "greenified" );

Be careful , The concept of conjunction does not apply to jQuery Tool method , for example :$.trim().

Protect $Alias And add scope

stay JavaScript In the class library , $ Variables are very popular , If you are using jQuery At the same time using other class libraries , You may have to use jQuery.noConflict() Methods to make jQuery No longer use $ Variable . However , This will disrupt our plugins , Because it assumes $ yes jQuery In the case of alias . In order to be compatible with other plug-ins , And still use jQuery Of $ Alias , We need to put all the code in the function expression that we call immediately (Immediately Invoked Function Expression) among , And then transfer jQuery function , And will $ As a parameter :

 (function ( $ ) {
$.fn.greenify = function() {
this.css( "color", "green" );
return this;
}; $.ltrim = function( str ) {
return str.replace( /^\s+/, "" );
}; $.rtrim = function( str ) {
return str.replace( /\s+$/, "" );
}; }( jQuery ));

Besides , The main purpose of immediate function expressions is to allow us to have our own private variables . Suppose we need a different green color , And I want to store it in a variable .

 (function ( $ ) {
var shade = "#556b2f";
$.fn.greenify = function() {
this.css( "color", shade );
return this;
}; }( jQuery ));

Minimize plug-in footprint

When writing plug-ins , The best practice is to take only one $.fn Expansion slot . This reduces the chance that the plug-in will be covered , It also reduces the chance of covering other plug-ins . let me put it another way , The following is not appropriate :

 (function( $ ) {
$.fn.openPopup = function() {
// Open popup code.
}; $.fn.closePopup = function() {
// Close popup code.
}; }( jQuery ));

It is more reasonable to use only one expansion slot , Use parameters to control what the expansion slot does .

 (function( $ ) {
$.fn.popup = function( action ) {
if ( action === "open") {
// Open popup code.
} if ( action === "close" ) {
// Close popup code.
} }; }( jQuery ));

Use each() Method

The standard jQuery Object will contain any number of DOM Reference to element , That's why jQuery Objects are often treated as collections . If you want to do anything with a specific set of elements ( for example , Get one data attribute , Calculate specific properties, etc ) At this point you need to use .each() Method to traverse the set of elements .

 $.fn.myNewPlugin = function() {
return this.each(function() {
// Do something to each element here.
}); };

It should be noted that , We go back to .each() Method instead of returning this . because .each() The method is connectable , It will return this , And we go straight back this It's the same . This is the best practice we've done so far to stay connected .

Accept the option

As plug-ins get more and more complex , It's a good idea to make plug-ins customizable through options . Especially when there are many options , The simplest way is to use the literal amount of the object (object literal). Let's make some changes to the plug-in , Make it accept some options .

 (function ( $ ) {
$.fn.greenify = function( options ) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
color: "#556b2f",
backgroundColor: "white"
}, options ); // Greenify the collection based on the settings variable.
return this.css({
color: settings.color,
backgroundColor: settings.backgroundColor
}); }; }( jQuery ));

Examples of use :

 $( "div" ).greenify({
color: "orange"

color The default value of #556b2f adopt $.extend() Method is covered , And it turns orange .

Complete implementation

Here is an example of a small plug-in , It uses some of the techniques we discussed earlier :

 (function( $ ) {
$.fn.showLinkLocation = function() {
return this.filter( "a" ).each(function() {
$( this ).append( " (" + $( this ).attr( "href" ) + ")" );
}); }; }( jQuery )); // Usage example:
$( "a" ).showLinkLocation();

This handy plug-in will traverse all anchors in the collection , And then href Attributes are appended to parentheses .

 <!-- Before plugin is called: -->
<a href="page.html">Foo</a> <!-- After plugin is called: -->
<a href="page.html">Foo (page.html)</a>

The plug-in can also be optimized as follows :

 (function( $ ) {
$.fn.showLinkLocation = function() {
return this.filter( "a" ).append(function() {
return " (" + this.href + ")";
}); }; }( jQuery ));

We will use .append() Method to accept a callback function , And the return value of the callback function depends on the content attached to each element in the collection . It should be noted that , At the same time, we didn't use .attr() How to get href attribute , Because of the original DOM API So that we can easily access the properly named href attribute .

Original address :http://learn.jquery.com/plugins/basic-plugin-creation/

jQuery How to create basic plug-ins ( translate ) More articles about

  1. jQuery Custom scroll bar style plug-in mCustomScrollbar

    If you build a unique and creative web page , You want to define the scroll bar style in the web page , In this respect jQuery Plug in is quite good , There are two :jScrollPane  and  mCustomScrollbar. About jScro ...

  2. Powerful support for multi file upload jQuery File upload plugin Uploadify

    Support multi file upload jQuery File upload plugin Uploadify, At present, there are two versions of this plug-in, namely Flash Version and HTML5 edition , about HTML5 Version will support mobile browser better , Avoid Apple phones Safari Browser does not support Fla ...

  3. jQuery File upload plugin Uploadify( turn )

    Based on a flash File upload of , There are progress bar and support large file upload , And can upload multiple files to the queue . This one is in flash That's an increase from html5 Support for , So it can also be used on the mobile end . Because the official version is flash free ,html5 ...

  4. jQuery Build intelligent prompt plug-in 2 ( Edit drop-down box )

    In the last article jQuery Build intelligent prompt plug-in   Improve on , Add drop-down button , Fixed click drop-down area not hidden BUG effect Drop down button : js encapsulation , Note that the red part is BUG Repair , Then incoming boxwidth No px: /* /// ...

  5. 12 This is a classic white Fumei model —jquery Image carousel plug-in — Necessary for front-end development

    Image carousel is a common function in websites , Used to display a group of product pictures or photos in limited web space , At the same time, there are also very attractive animation effects . This article recommends 12 It's practical  jQuery  Image carousel effect plug in , Help you add some beautiful effects to your project ...

  6. jQuery File upload plugin jQuery Upload File There's an upload progress bar

    jQuery File upload plugin jQuery Upload File There's an upload progress bar jQuery File upload plugin jQuery Upload File, Plug ins are easy to use , Support single file and multi file upload , Support file drag upload , There is progress ...

  7. 【jquery】Validform, A good one jquery Form validation plug-in

    About Validform This is a very good one jquery Form validation plug-in , It can satisfy almost any verification requirement , Only one line of code can complete the form verification of the whole station . $('form').Validform(); Why is it so convenient ...

  8. 【jQuery Based on learning 】06 jQuery Form validation plug-in -Validation

    jQuery I have finished the basic part of , So it's up to the plug-in . About jQuery Form validation plug-in -Validation validation characteristic : Built in validation rules : Ownership is required . Numbers .E-Mail.URL And credit card numbers 1 ...

  9. jQuery extend() &amp; jQuery.fn.extend(), Plug in writing

    source : Online data sorting and self adaptation test . Copy the following code and rely on jquery.js,jquery.validate.js Can execute . What's wrong , please @ Me , Please give me your advice . <!DOCTYPE html PUBLI ...

Random recommendation

  1. Android Call the system camera to take pictures and video

    This paper implements android System camera call to take pictures The layout of the project is quite simple , only one Button: <RelativeLayout xmlns:android="http://schemas.a ...

  2. XsltListViewWebPart And custom list view


  3. use tcc A big hole I met

    stay centos6.5 x86_64 After compiling and installing on the server tcc, edition 0.9.25( stay github On clone Of ), It seems that everything is normal But for use tcc To compile the "hello, world" The program , ...

  4. Wamp Environment build common error problem solving

    The first point . about apache + php + mysql The right choice of the version of problem : Some teaching videos on the Internet are very early , And then a lot of people follow , It's exactly the same as in the video , But the result is that it doesn't work . The cause of the problem : Version selection of the three piece set ...

  5. software test 4gkd

    One . There are several types of performance testing , What's the relationship between them ? (1) Performance testing includes : The load test . Pressure test . Configuration testing . Concurrent test . Capacity test . Reliability test . Failed tests . The load test : By gradually increasing the load on the system , Test for changes in system performance , And finally ...

  6. vscode Create the best markdown Editor

    Reference resources :https://www.jianshu.com/p/18876655b452 stay macos It's also set up successfully :

  7. border Special use of

    It's easy to see a small triangle on the secondary menu on some web pages , This little triangle In addition to using pictures or using iconfont Write out , You can also use border Write out Here is a simple example , I hope it works for you ! css ...

  8. [na]802.1x Protocol wireless authentication protocol &amp;dot1x Wired authentication experiment

    When we used to do wireless , It's going to involve wireless client Authentication protocol of access mode . authentication + encryption + Wired dot1x. notes : It used to be doc Posted to the blog , Plus no blogging habits , So it's going to be messy . EAP( Extended authentication protocol ) What is it? ? ...

  9. flash Code

    Flash Common action command one .Flash Common commands in :1. Stop playing at the current frame on(release){ stop();} 2. Play from the current frame on(release){ play();} 3. Jump to the first 10 ...

  10. Android It can improve the efficiency of study

    A friend in Zhihu asked Android Can we improve our study in the future . What are the applications of work efficiency ? The recommendation I gave them got the most approval . This post will be improved and updated in the future . Any.do : Planning schedule , Every platform has . Evernote: Note taking , Every platform has ...