Basic Javascript knowledge in Jquery source code (4)-jQuery. fn. init method, jquery. fn. init

Source: Internet
Author: User

Basic Javascript knowledge in Jquery source code (4)-jQuery. fn. init method, jquery. fn. init

$ () Indicates that the jQuery. fn. init method is called.

jQuery = function( selector, context ) {    return new jQuery.fn.init( selector, context, rootjQuery );}

The init method code is as follows:

 1 init: function( selector, context, rootjQuery ) { 2     var match, elem; 3     if ( !selector ) { 4         return this; 5     } 6     if ( typeof selector === "string" ) { 7         // code 8     } else if ( selector.nodeType ) { 9         this.context = this[0] = selector;10         this.length = 1;11         return this;12     } else if ( jQuery.isFunction( selector ) ) {13         return rootjQuery.ready( selector );14     }15     if ( selector.selector !== undefined ) {16         this.selector = selector.selector;17         this.context = selector.context;18     }19     return jQuery.makeArray( selector, this );20 }

We can see that all possible values of the selector parameter are judged.

1. Whether it is an error value, such as: $ (""), $ (null), $ (undefined), $ (false ).

2. Whether it is a string.

3. Whether it is a node Element Object. For example, $ (this), $ (document ).

4. Whether it is a function. For example, $ (function (){}).

5. Whether it is a jQuery object. For example, $ (element )).

6. Whether it is an array or json.

 

When the parameter is a string

If (typeof selector = "string") {if (selector. charAt (0) = "<" & selector. charAt (selector. length-1) ==="> "& selector. length >=3) {match = [null, selector, null];} else {match = rquickExpr.exe c (selector );} // create an element or select ID if (match & (match [1] |! Context) {// create element if (match [1]) {// code // select ID} else {// code} // other selector} else if (! Context | context. jquery) {return (context | rootjQuery). find (selector);} else {return this. constructor (context). find (selector );}}

First, assign a value to the variable match.

First case

if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {    match = [ null, selector, null ];}

The charAt method returns characters at the specified position. The following is a qualified string:

"<Div>", "<div> </div>", "<div> 111 </div>"

Case 2

match = rquickExpr.exec( selector );

RquickExpr has been defined earlier

rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,

This syntax creates a RegExp object

After the exec method finds the Matching content, an array is returned, including the complete matching of the expression and matching of the subexpression. Otherwise, null is returned. The following is a qualified string:

"<Div> 111", "# id"

Next, let's look at the code below:

If (match & (match [1] |! Context) {if (match [1]) {// code creation element} else {// code selection ID }}

From the analysis of the value assignment of match, we can know that

In this example, we use the following methods to create elements and Select IDS:

$ ('<Div>'), $ ('# id ')

Another internal if-else statement processes the creation element and the selection ID respectively.

See the process creation element section below:

if ( match[1] ) {    context = context instanceof jQuery ? context[0] : context;    jQuery.merge( this, jQuery.parseHTML(        match[1],        context && context.nodeType ? context.ownerDocument || context : document,        true    ) );    if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {        for ( match in context ) {            if ( jQuery.isFunction( this[ match ] ) ) {                this[ match ]( context[ match ] );            } else {                this.attr( match, context[ match ] );            }        }    }    return this;}

Here we will briefly introduce parseHTML and merge methods.

The jQuery. parseHTML method is used to convert a string into a node array, for example:

The jQuery. merge method is generally used to merge arrays.

Json can also be merged here

However, the json format has some special characteristics and needs to be similar to the following:

var obj = {    0 : 'a',    1 : 'b',    length : 2}

After jQuery is used to select or create elements, the jQuery object creates an array-like structure for the node elements, facilitating subsequent operations.

There is still a piece of code going forward:

if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {    for ( match in context ) {        if ( jQuery.isFunction( this[ match ] ) ) {            this[ match ]( context[ match ] );        } else {            this.attr( match, context[ match ] );        }    }}

This code is used to add attributes to element tags, for example:

First Condition

rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,

The test () method is used to check whether a string matches a certain pattern. If yes, true is returned. If no, false is returned.

Strings that match the regular expression are as follows:

"<Div>", "<div> </div>", that is, a single tag.

 

Second condition

JQuery. isPlainObject (context) determines whether the second parameter is an object literal.

Then... an in statement traverses attributes in an object. If a method with the same name as an attribute exists, this method is called (for example, the html method is called in the preceding example). Otherwise, the attr method is called.

 

The creation element is here. Next, select the id.

if ( match[1] ) {    // code} else {    elem = document.getElementById( match[2] );    if ( elem && elem.parentNode ) {        // Inject the element directly into the jQuery object        this.length = 1;        this[0] = elem;    }    this.context = document;    this.selector = selector;    return this;}

This is simple. You can directly use the getElementById method to obtain the target element and assign values accordingly to create an array-like structure.

In addition to creating elements and selecting IDs

if ( match && (match[1] || !context) ) {    // code} else if ( !context || context.jquery ) {    return ( context || rootjQuery ).find( selector );} else {    return this.constructor( context ).find( selector );}

We can see that no matter which branch is followed, the find method is called. Therefore, selecting classes, selecting elements and more complex selectors are not processed in the init method, instead, find is called, which will be discussed later.

Finally, let's take a look at the other conditions of parameters except strings:

if ( typeof selector === "string" ) {    // code} else if ( selector.nodeType ) {    this.context = this[0] = selector;    this.length = 1;    return this;} else if ( jQuery.isFunction( selector ) ) {    return rootjQuery.ready( selector );}if ( selector.selector !== undefined ) {    this.selector = selector.selector;    this.context = selector.context;}return jQuery.makeArray( selector, this );

When the parameter is an element object or jQuery object, assign values to some attributes.

When the parameter is a function, the ready method is called,

Therefore, $ (function () {}) is a shorthand for loading $ (document). ready (function.

The makeArray method is similar to the previously mentioned merge method. It can be used to convert node elements into arrays.

It can also be converted to json, and the second parameter must be in the form of an array of classes.

Okay. To sum up, jQuery. fn. the init method processes different types of parameters. When the parameter is a string, it mainly processes the creation element and selection id internally. In other cases, it is handed over to the find method, finally, a class array structure about node elements and initialization of some attributes are constructed.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.