Jquery Advanced Programming (3)

Keywords: JQuery JSON PHP Attribute

Description and application of jquery advanced method

1.addBack()

A. Several adjacent nodes under li of third-item (including third-item)

$( "li.third-item" ).nextAll().addBack(). 
 .css( "background-color", "red" ); 

b. Similar to the end() method, the div.after-addback and p elements are selected, and the div.after-addback element is selected by the end.

$( "div.after-addback").find("p").addBack().addClass("background"); 
$( "div.after-addback").find("p").end().addClass("background"); 

2.callback.fire()

Calling foo functions by parameters

var foo = function(value){ 
  console.log( "foo:" + value ); 
} 
var callbacks = $.Callbacks(); 
callbacks.add(foo); 
callbacks.fire("hello"); 
callbacks.fire("world"); 

3.callback.lock()

Lock the list of callback functions, which cannot accept any parameters.

var foo = function( value ) { 
 console.log( "foo:" + value ); 
}; 
var bar = function( value ){ 
 console.log( "bar:" + value ); 
}  
var callbacks = $.Callbacks(); 
callbacks.add( foo ); 
callbacks.fire( "hello" ); // Output "foo: hello" 
callbacks.lock(); // You can't call foo methods after that unless $. Callbacks("memory") add s a function 
callbacks.fire( "world" ); // No foo method was called 
callbacks.add( bar ); // When callbacks are assigned a value of $. Callbacks("memory"), create a callback object and use the memory identifier to add another function. 
callbacks.fire( "world" ); // Output "bar: hello" 

4.defered.promise()

Return another Deferred object on the original Deferred object

$(function(){ 
  $("input[type=button]").click(function(){ 
    $.ajax({ 
      url : "validate.html", 
      type : "POST", 
      dataType : "json" 
    }).done(function(data){ 
      alert(data.a); 
    }).fail(function(){ 
      alert("error"); 
    }) 
  }); 

  var dtd = $.Deferred(); 
  var wait = function(dtd){ 
    var tasks = function(){ 
      alert("Execution finished!"); 
      dtd.resolve(); // Changing the execution state of Deferred objects 
    }; 
      setTimeout(tasks,5000); 
   }; 
   dtd.promise(wait); 
   wait.done(function(){ alert("Haha, success!"); }).fail(function(){ alert("Error!");  
}); 

5.animate({ step : function(){ } })

Animation of one element while animating another element

$( "#go" ).click(function() { 
 $( ".block:first" ).animate({ 
  left: 100 
 }, { 
  duration: 1000, 
  step: function( now, fx ){ 
   $( ".block:gt(0)" ).css( "left", now ); 
  } 
 }); 
}); 

6.clone()

Use it in conjunction with the appendTo method to create a cloned element

<div class="container"> 
 <div class="hello">Hello</div> 
 <div class="goodbye">Goodbye</div> 
</div> 

$( ".hello" ).appendTo( ".goodbye" ); 

The result is:

<div class="container"> 
 <div class="goodbye"> 
  Goodbye 
  <div class="hello">Hello</div> 
 </div> 
</div> 
$( ".hello" ).clone().appendTo( ".goodbye" ); 

The result is:

<div class="container"> 
 <div class="hello">Hello</div> 
 <div class="goodbye"> 
  Goodbye 
  <div class="hello">Hello</div> 
 </div> 
</div> 

jquery's advanced selection based on name attribute

$("div[id]") Select all div elements with ID attributes
("input[name='keleyicom']) Select the input element whose name attribute equals'keleyicom'.

("input[name!='keleyicom']) Select all input elements whose name attribute is not equal to'keleyicom'.

$("input[name^='keleyi']) Select all input elements whose name attribute begins with'keleyi'.
("input[name$='keleyi'])") Select the input element whose name attribute ends with'keleyi'.
("input[name*='keleyi']) Select all name attributes that contain the input element of'keleyi'.
$("input[id][name$='keleyi']) can use multiple attributes for joint selection, the selector is the element that gets all the ID attributes and then the attributes end in keleyi

For example: $(": input[name='keleyi']") means that the form whose name is keleyi is looked up.

jQuery Advanced Events

I. Simulated Operation

Simulate user start button operation:.trigger() and. triggerHandler()

Register button event:

//Click on the button event
$('input').click(function () {
alert('My first click came from simulation!');
});

//Simulate user click behavior

$('input').trigger('click');

//Merge registration and click behavior

$('input').click(function () {
alert('My first click came from simulation!');
}).trigger('click');

Pass multiple parameters:

$('input').click(function (e, data1, data2) {
alert(data1+", "+data2.key);
}).trigger('click', ['abc', {key: 'value'}]);

// Custom Events

$('input').bind("myEvent",function () {
alert('myEvent occurred');
}).trigger('myEvent');

The abbreviation scheme of the trigger() method is as follows: trigger('click'); can be abbreviated as. click();

$('input').click(function () {
alert('My first click came from simulation!');
}).triggerHandler('click');

The difference between. trigger() and. triggerHandler():

  1. The triggerHandler does not trigger the default behavior of the event, but the trigger triggers.
  2. triggerHandler only calls the event method of the first matched element, while trigger calls the event method of all matched elements.
  3. triggerHandler returns the return value of the current event execution, undefined if there is no return value, and trigger returns the jQuery object that currently contains the event trigger element (convenient chain connection call);
  4. trigger bubbles when creating events; triggerHandler does not bubbles;

Namespaces

Purpose: Used to resolve events that remove the same name and element bindings.

$('input').bind('click.abc', function(){

alert('abc');

});

$('input').bind('click.xyz', function(){

alert('xyz');

});
//Remove event handlers with. abc namespace from click events

$('input').unbind('click.abc');

$('input').trigger('click.abc');

III. Incident Entrustment

BACKGROUND: Events in html have bubbling behavior and transfer from the bottom to the top. So the parent element can get the events of the child element, and through event.type and event.target, you can know which child element produces what kind of events.

Applying this mechanism, we can register specific types of events in html by delegating events to specified parent elements.

Usage method:

$('#box').delegate('.targetClass', 'click', function() {});//The ID is an element of box, and the proxy executes click events for sub-elements of targetClass.

$('#box').undelegate('.targetClass', 'click');//Cancel the proxy for click events of elements with ID box to sub-elements with type targetClass.

Be careful:

  1. delegate needs to specify the parent element. The first parameter is the current element, the second parameter is the event type, and the third parameter is the processing function.
  2. Like unbind, undelegate can delete all events directly, use undelegate('click') to delete all click events, or delete events in command space, such as undelegate('click.abc') to delete click events in. abc;

Scope of use:

  1. In DOM, a large number of elements need to bind the same event.
  2. There is no element binding event to be generated in DOM.

on/off/one

These three methods are used to replace methods: bind()/unbind(), live()/die(), delegate()/undelegate().

//

$('.button').on('click', function(){});

$('.button').on('click mouseover', {user:'alan'}, function(){});//Binding multiple events to specify additional data

$('.button').on({

'click': function(){},

'mouseover': function(){},

});//Binding multiple events as objects

$('.button').on('submit', function(){ return false});//Prevent default behavior and remove bubbles

$('.button').on('click', false);//Prevent default behavior and remove bubbles


$('.button').off('click');//Cancel all click processing methods

$('.button').off('click', fn);//unbind, cancel the specific processing method fn

$('.button').off('click.abc');//Canceling Namespaces


$('#box').on('click', '.button', function());//Instead of live/delegate, event delegate

$('#box').off('click', '.button');//Replace die/undelegate to cancel event delegation


$('#box').one('click', '.button', function());//Only one event is processed, and then the event handling method fails. (For example, a button event, the first click of a button invokes the method processing, which is then removed)

jquery ajax example tutorial and some advanced usage

jquery ajax invocation: jquery.ajax(url,[settings]), jquery ajax common parameters: red markup parameter almost every Ajax request will use these parameters, this article will introduce more examples of jquery ajax, followed by some advanced uses of Ajax

query ajax invocation: jquery.ajax(url,[settings]), because the actual use of the process often configures not many, so there is no list of all parameters, or even some parameters default values, is best practice, there is no need to define their own, unless there are special requirements, if you need all parameters, you can see the jquery api

$.ajax({
    url: "test.html",  //ajax request address
    cache: false,//(Default: true, default is false when dataType is script and jsonp.) Setting false will not cache this page, it is recommended to use default
    type:"GET",//Request mode "POST" or "GET", default to "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used, but only some browsers support them.
    dataType:"json",    //These types are optional depending on the type of data returned: xml html script json jsonp text
    //The data sent to the server can be passed directly to the object {a:0,b:1}, and if it is a get request, it will be automatically spliced behind the url, such as: & A = 0 & B = 1
    //If it is an array, jQuery automatically corresponds to the same name for different values. For example, {foo:["bar1", "bar2"]} is converted to "& foo = bar1 & foo = bar2".
    data:{},
    //Before sending a request, you can modify the function of the XMLHttpRequest object, such as adding a custom HTTP header. The XMLHttpRequest object is the only parameter. This is an ajax event. If you return false, you can cancel this ajax request.
    beforeSend:function(xhr){
        //This defaults to the options parameter passed when calling this AJAX request
    },
    //Context This object is used to set the context of the ajax-related callback function. That is to say, let this point to this object in the callback function (if this parameter is not set, then this points to the options parameter passed when calling this AJAX request).
    //For example, specifying a DOM element as the context parameter sets the context of the success callback function as the DOM element.
    context: document.body,
    //Callback function after successful request
    success: function(data,textStatus){
        //This calls the options parameter passed in this AJAX request, and if context is set to change this, this is changed here.
    },
    //Call this function when the request fails. There are three parameters: XMLHttpRequest object, error message, and (optionally) captured exception object.
    //If an error occurs, the error message (the second parameter) may be "timeout", "error", "notmodified" and "parsererror" in addition to null.
    error: function(XMLHttpRequest, textStatus, errorThrown){
        // Usually in textStatues and errorThrown
        // Only one will contain information.
        // This calls the options parameter passed in this AJAX request
    },
    //Callback function after the request is completed (call after the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request
    complete:function(XMLHttpRequest, textStatus) {
        //This calls the options parameter passed in this AJAX request
    },
    //A set of numeric HTTP codes and function objects that are called in response. For example, if the response state is 404, the following alerts will be triggered:
    statusCode:{
        404:function(){
            alert('404,Page does not exist');
        }
    }
});

jquery ajax sends a get request and the data returns to json

ajax is the most commonly used way to get data in actual combat, and get is the most common way.

$.ajax({
    type: "GET",
    url: "page.php",
    dataType:'json',
    data: {id:1001},//It can also be a string link "id=1001", and it is recommended to use objects.
    success: function(data){
        console.log("Data returned: " + data );
    }
});

jquery ajax sends a post request and the data returns to json

The most commonly used method of submitting data in actual combat is ajax, and the general way of submitting data is post.

$.ajax({
    type: "POST",
    url: "page.php",
    dataType:'json',
    data: {name:"Zhang San",sex:1},//It can also be a string link "name = Zhangsan & sex = 1", which is recommended to use objects.
    success: function(data){
        //In practice, the returned json object may have a judgment flag for success errors, so you may need to make a judgment as well.
        console.log("Data returned: " + data );
    }
});

jquery ajax sends a get request in short:

Actually, it's the second encapsulation of ajax. You can compare the underlying api of Ajax

//$.get("request url","Data object sent","Successful callback","Return data type");
$.get("test.cgi",{ name: "John", time: "2pm" },
   function(data){
      alert("Data Loaded: " + data);
},'json');

jquery ajax sends a POST request in short:

Actually, it's the second encapsulation of ajax. You can compare the underlying api of Ajax

//$.post("request url","Data object sent","Successful callback","Return data type");
$.post("test.cgi",{ name: "John", time: "2pm" },
   function(data){
      alert("Data Loaded: " + data);
},'json');

A tool function commonly used in jquery ajax

When ajax submits data, it usually submits a form, so serializing form data is very useful, such as: $("form"). serialize().

//Complete examples such as: (Form html structure is not written)
    $("form").on("submit",function(){
        var url = this.action;   //Actions that can be fetched directly from the form
        var formData = $(this).serialize();
        $.post(url,formData,
            function(data){
                //Back to success, you can do something else.
                console.log(data);
            },'json');

        //Prevent form default submission behavior
        return false
    })

jquery ajax requests successful callbacks rewritten to join.

ajax request success is usually handled by callbacks, but in jquery, you can also use links instead of callbacks. As follows:

//This parameter can be a function or an array of functions. When the delay succeeds, the function in the done is called. Callbacks are executed in the order they are added.
//Once deferred.done() returns the deferred object, other methods of deferred object can also be linked here, including adding. done() methods. When delays are resolved, web front-end development
$.get("ajax.php").done(function() {
    //Delayed success
    alert("ok");
}).fail(function(){
    //Delay failure;
    alert("$.get failed!");
});

jquery ajax linking also has a two-in-one method. then,. then can also write more than one. then. then can use the results in the previous. then

$.get("test.php").then(
    function(){
        //Delayed success
    },
    function(){
        //Delay failure;
    }
);

jquery ajax also has a jQuery.when method

Provides a way to execute a callback function for one or more objects, delayed objects usually represent asynchronous events. If a single delay is passed to jQuery.when, it is returned by the bound callback function, such as defered.then, accessed through this method and other methods attached to the defered object.
When the delay is resolved or rejected, the usual code creates the original delay, and the appropriate callback is invoked. As follows:

//Two complete requests are successful before the callback is executed. This API is described in detail below the "Tools" column of the jquery api.
$.when($.ajax("p1.php"), $.ajax("p2.php"))
  .then(function(){
        //Two complete requests succeeded
    }, function(){
        //Any execution failure
    });

A real-world example of jquery ajax, where Ajax request services are centralized into service.js

Here, jquery ajax requests are written as a service, such as the following code in service.js:

//Every time we repeat the ajax code and some data processing, the global prompt can be written here, of course, there is no business logic, only do some data processing and part of the prompt.
function myService(){
    return {
        query: function (data) {
            var _data = data||{};
            return $.get("test.php",_data).then(
                    function(){//Delayed success}
                    function(){//Delay failure;}
                );
        },
        submit: function (data) {
            var _data = data||{};
            return $.post("test.php",_data).then(
                    function(){},
                    function(){}
                );
        }
    }
}
//Of course, the code should be modularized rather than declaring a global myService directly

1. Class-level plug-in development

The most direct understanding of class-level plug-in development is to add class methods to jQuery classes, which can be understood as adding static methods. A typical example is the $. AJAX() function, which is defined in jQuery's namespace.
Plug-in development at the class level can be extended in the following forms:

1.1 Add a new global function

To add a global function, we need only the following definitions:

  jQuery.foo = function() {   
     alert('This is a test. This is only a test.');  
     };    

1.2 Adding more than one global function

Adding multiple global functions can be defined as follows:

    jQuery.foo = function() {   
     alert('This is a test. This is only a test.');  
     };  
     jQuery.bar = function(param) {   
     alert('This function takes a parameter, which is "' + param + '".');  
     };   
     The call is the same as a function: jQuery.foo();jQuery.bar(); or $. foo();$.bar('bar');  

1.3 Use jQuery.extend(object);

     jQuery.extend({      
     foo: function() {      
     alert('This is a test. This is only a test.');      
     },      
     bar: function(param) {      
     alert('This function takes a parameter, which is "' + param +'".');      
     }     
     });  

1.4 Use namespaces

Although in the jQuery namespace, we prohibit the use of a large number of javaScript function names and variable names. However, it is still inevitable that some function or variable names will conflict with other jQuery plug-ins, so we are used to encapsulating some methods into
Another custom namespace.

  jQuery.myPlugin = {          
     foo:function() {          
     alert('This is a test. This is only a test.');          
     },          
     bar:function(param) {          
     alert('This function takes a parameter, which is "' + param + '".');    
     }         
     };  

The function using namespace is still a global function, and the method used when calling is as follows:

  $.myPlugin.foo();         
     $.myPlugin.bar('baz');  

With this technique (using separate plug-in names), we can avoid conflicts of functions in namespaces.

2. Object-level plug-in development

Object-level plug-in development requires the following two forms:
Form 1:

   (function($){     
     $.fn.extend({     
     pluginName:function(opt,callback){     
               // Our plugin implementation code goes here.       
     }     
     })     
     })(jQuery);     

Form 2:

  (function($) {       
     $.fn.pluginName = function() {     
          // Our plugin implementation code goes here.     
     };     
     })(jQuery);      

It defines a jQuery function with a parameter of $. When the function definition is completed, pass in the jQuery parameter. Call execution immediately. The advantage is that when we write jQuery plug-ins, we can also use the alias of $without clashing with prototype.

2.1 Declare a name under the JQuery namespace

This is a script for a single plug-in. If your script contains multiple plug-ins or reciprocal plug-ins (e.g. $. fn.doSomething() and $. fn.undoSomething()), you need to declare multiple function names. However,
Usually when we write a plug-in, we try to use only one name to contain all its content. Our sample plug-in is named "highlight"“

     $.fn.hilight = function() {    
       // Our plugin implementation code goes here.    
     };    
     Our plug-in is called in this way:  
     $('#myDiv').hilight();     

But what if we need to decompose our implementation code into multiple functions? There are many reasons: design needs; easier or more readable implementations; and more object-oriented. It's a real hassle.
Functional implementations are decomposed into multiple functions without adding additional namespaces. To recognize and utilize functions as the most basic class object in javascript, we can do this. Like other objects, functions can be specified as attributes.
So we have declared "hilight" as jQuery's attribute object. Any other attribute or function we need to expose can be declared in the "hilight" function. Continue later.

## 2.2 Accept options parameters to control plug-in behavior

Let's add functionality to our plug-in that specifies foreground and background colors. We might pass the options like an options object to the plug-in function. For example:

  // plugin definition    
     $.fn.hilight = function(options) {    
       var defaults = {    
         foreground: 'red',    
         background: 'yellow'    
       };    
       // Extend our default options with those provided.    
       var opts = $.extend(defaults, options);    
       // Our plugin implementation code goes here.    
     };    
     //Our plug-in can be called in this way:  
     $('#myDiv').hilight({    
       foreground: 'blue'    
     });     

2.3 Expose the default settings for plug-ins

One improvement we should make to the above code is to expose the default settings of the plug-in. This makes it easier for plug-in users to cover and modify plug-ins with less code. Next we start using function objects.

    // plugin definition    
     $.fn.hilight = function(options) {    
       // Extend our default options with those provided.    
       // Note that the first arg to extend is an empty object -    
       // this is to keep from overriding our "defaults" object.    
       var opts = $.extend({}, $.fn.hilight.defaults, options);    
       // Our plugin implementation code goes here.    
     };    
     // plugin defaults - added as a property on our plugin function    
     $.fn.hilight.defaults = {    
       foreground: 'red',    
       background: 'yellow'    
     };     
 Now users can include a line like this in their scripts:  
    //This only needs to be called once, and not necessarily in the read block.  
     $.fn.hilight.defaults.foreground = 'blue';    
 Next we can use the plug-in method like this, and as a result it sets the blue foreground color:  
  $('#myDiv').hilight();   

As you can see, we allow users to write a line of code in the default foreground color of the plug-in. And users still have the option to override these new defaults when they need to:

 // Override the default background color of the plug-in 

 $.fn.hilight.defaults.foreground = 'blue'; 

 // ... 

 // Call the plug-in with a new default setting 

 $('.hilightDiv').hilight(); 

 // ... 

 // Override default settings by passing configuration parameters to plug-ins 

 $('#green').hilight({ 

   foreground: 'green' 

 });  

2.4 Properly expose some functions
This section will step by step extend your plug-in in an interesting way to the previous section of code (while allowing others to extend your plug-in at the same time). For example, in the implementation of our plug-in, we can define a function called format to format highlighting.
Text. Our plug-in now looks like this, and the implementation of the default format method is under the hiligth function.

   // plugin definition    
     $.fn.hilight = function(options) {    
       // iterate and reformat each matched element    
       return this.each(function() {    
         var $this = $(this);    
         // ...    
         var markup = $this.html();    
         // call our format function    
         markup = $.fn.hilight.format(markup);    
         $this.html(markup);    
       });    
     };    
     // define our format function    
     $.fn.hilight.format = function(txt) {    
     return '<strong>' + txt + '</strong>';    
     };     
   It's easy to support other properties in options objects by allowing a callback function to override the default settings. This is another great way to modify your plug-in. The technique shown here is further effective exposure.
   The format function then allows him to be redefined. With this technique, other people can pass their own settings over your plug-ins, in other words, so that others can write plug-ins for your plug-ins. Consider this passage.
   The useless plug-ins we built in this chapter, you may want to know exactly when these will be useful. A real example is the Cycle plug-in. This Cycle plug-in is a sliding display plug-in that supports many internal transformations to
   Rolling, sliding, gradual disappearance, etc. But in fact, there is no way to define the effects that might apply to each type of slip change. That's where this extensibility is useful. Cycle plug-ins expose "transitions" to users
   Objects that enable them to add their own transformed definitions. The definition in the plug-in is like this:
 $.fn.cycle.transitions = { 

 // ... 

 }; 

This technique enables others to define and pass transformation settings to the Cycle plug-in.

2.5 Keeping Private Functions Private

This technique is very powerful for exposing part of your plug-in to be covered. But you need to think carefully about the exposed parts of your implementation. Once exposed, you need to keep any changes to parameters or semantics in your mind that may undermine backwards.
Compatibility. One reason is that if you're not sure whether to expose a particular function, you probably don't need to do that. So how do we define more functions without scrambling namespaces and exposing implementations? This is the function of closures.
For demonstration, we will add another "debug" function to our plug-in. This debug function formats the selected elements for output to the firebug console. To create a closure, we wrap the entire plug-in definition
In a function.

      (function($) {    
       // plugin definition    
       $.fn.hilight = function(options) {    
         debug(this);    
         // ...    
       };    
       // private function for debugging    
       function debug($obj) {    
         if (window.console && window.console.log)    
           window.console.log('hilight selection count: ' + $obj.size());    
       };    
     //  ...    
     })(jQuery);    

Our "debug" approach is not accessible from external closures, so our implementation is private.

2.6 Supports Metadata Plug-ins

On the basis of the plug-in you're writing, adding support for the Metadata plug-in can make it more powerful. Personally, I like this Metadata plug-in because it lets you override the plug-in options with a few "markup" options (which is very useful).
When creating an example. And supporting it is very simple. Update: There are some optimization suggestions in the comments.

     $.fn.hilight = function(options) {    
       // ...    
       // build main options before element iteration    
       var opts = $.extend({}, $.fn.hilight.defaults, options);    
       return this.each(function() {    
         var $this = $(this);    
         // build element specific options    
         var o = $.meta ? $.extend({}, opts, $this.data()) : opts;    
         //...      

These changes do something: it tests whether the Metadata plug-in is installed or not, and if it is installed, it can extend our options object by extracting the metadata line and adding it to JQuery.extend as the last parameter.
Then it will override any other option settings. Now we can drive behavior from "markup" if we choose "markup":

When calling, you can write as follows: jQuery.foo(); or $. foo();

  <!--  markup  -->    
     <div class="hilight { background: 'red', foreground: 'white' }">    
       Have a nice day!    
     </div>    
     <div class="hilight { foreground: 'orange' }">    
       Have a nice day!    
     </div>    
     <div class="hilight { background: 'green' }">    
       Have a nice day!    
     </div>    
     //Now we can highlight which div s use only one line of script:  
     $('.hilight').hilight();     

2.7 Integration

Let's finish our example with the following code:

     // Create a closure    
     (function($) {    
       // Definition of plug-ins    
       $.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    
           markup = $.fn.hilight.format(markup);    
           $this.html(markup);    
         });    
       };    
       // Private function: debugging    
       function debug($obj) {    
         if (window.console && window.console.log)    
           window.console.log('hilight selection count: ' + $obj.size());    
       };    
       // Define exposed format functions    
       $.fn.hilight.format = function(txt) {    
         return '<strong>' + txt + '</strong>';    
       };    
       // defaults for plug-ins    
       $.fn.hilight.defaults = {    
         foreground: 'red',    
         background: 'yellow'    
       };    
     // Closure termination    
     })(jQuery);     

This design has enabled me to create powerful and standard plug-ins. I hope it will enable you to do the same.

3. Summary

jQuery proposes two ways to develop plug-ins, namely:

jQuery.fn.extend(object); add methods to jQuery objects.
jQuery.extend(object); add new methods to the class to extend the jQuery class itself.

3.1 jQuery.fn.extend(object);

What is fn? Looking at jQuery code, it's not hard to find.

 jQuery.fn = jQuery.prototype = {  

 init: function( selector, context ) {//....   

 //......  

 };   

The original jQuery.fn = jQuery.prototype. Although javascript does not have a clear concept of classes, it is more convenient to understand them with classes. JQuery is a very well-encapsulated class.
For example, we use the statement $(" btn1") to generate an instance of the jQuery class.

jQuery.fn.extend(object); jQuery.prototype is extended to add "member functions" for jQuery classes. An instance of the jQuery class can use this "member function".

For example, we want to develop a plug-in to make a special edit box, when it is clicked, alert the contents of the current edit box. This can be done:

 $.fn.extend({        

      alertWhileClick:function(){       

          $(this).click(function(){      

               alert($(this).val());       

           });       

       }       

 });   
(" input1").alertWhileClick(); // On the page: <input id= "input1" type= "text"/>

The $("# input1") is a jQuery instance. When it calls the member method alertWhileClick, it implements an extension, which pops up the contents of the current edit each time it is clicked.

3.2 jQuery.extend(object); 

Adding class methods to jQuery classes can be understood as adding static methods. Such as:

 $.extend({  

     add:function(a,b){return a+b;}  

 });  

Add a "static method" for jQuery, and then you can use this method where jQuery is introduced, $. add(3,4); //return 7

Posted by omerta on Fri, 28 Jun 2019 12:48:34 -0700