Home >Web Front-end >JS Tutorial >Analysis of addClass() method of jQuery source code interpretation_jquery

Analysis of addClass() method of jQuery source code interpretation_jquery

WBOY
WBOYOriginal
2016-05-16 16:13:281483browse

This article analyzes the addClass() method of jQuery source code interpretation in more detail. Share it with everyone for your reference. The specific analysis is as follows:

Extend the addClass function to jQuery prototype object, jQuery.fn is jQuery.prototype

Copy code The code is as follows:
jQuery.fn.extend({
/*
It can be seen that this is a plug-in method with a function named addClass.
*/
AddClass: function( value ) {
        var classes, elem, cur, clazz, j, finalValue,
            i = 0,
/*
This represents the jQuery object selected by the selector to be added as a class, and len is the length of the jQuery object array.
*/
            len = this.length,
//When one operand is not a Boolean value, the && operation does not necessarily return a Boolean value. At this time, it follows the following rules:
//1. If the first operand is not of Boolean type, return the second operand;
//2. If the second operand is not of Boolean type, the object will be returned only if the evaluation result of the first operand is true;
//3. If neither operand is of Boolean type, return the second operand;
//4. If one of the operands is null, return null;
//5. If one of the operands is NaN, return NaN;
//6. If one of the operands is undefined, return undefined.
//Case 1: If value is null, which complies with rule 4, return null, that is, proceed value is null;
//Case 2: If value is undefined, which conforms to rule 6, undefined is returned, that is, the proceed value is undefined;
//Case 3: If value is NaN, which conforms to rule 5, return NaN, that is, proceed value is NaN;
//Case 4: If value is a numeric type, return false;
//Case 5: If value is a Boolean type, return false;
//Case 7: If value is Array, Object, Function type, it conforms to rule 2, but typeof value === 'string' is false, so the object is returned and false is returned.
//Case 8: If value is a string type and meets rule 2, return value.
//Therefore, this sentence can only determine whether the value is a string type, and return the string value to proceed. Any other type ends up returning false, or is a type that can be implicitly converted to false.
              proceed = typeof value === "string" && value;
//Since the above can only determine whether it is a string type, the following sentence is to determine whether the value is a Function type. The global function isFunction of jQuery is used to judge, which is $.isFunction().
            if ( jQuery.isFunction( value ) ) {
//If value is a Function type, go here.
//Return jQuery object for chain call.
//This here is the jQuery object selected by your selector.
               return this.each(function( j ) {
//Start iterating. This here is not a jQuery object, but the DOM object of the current iteration, so it is wrapped with jQuery(this) and becomes a jQuery object, so that you can use jQuery methods. j represents the index of each traversal. Pass a value function that returns a value to set the class name. The value function calls the current DOM as its execution object each time, and passes in the current DOM index value and class name. The value returned by the value function is called again by jQuery(this).addClass (return value). The addClass() method is called again. If a string is returned, another if branch is executed. If the returned function is still a function, continue to call the returned function.
jQuery( this ).addClass( value.call( this, j, this.className ) );
            });
}
//The proceed obtained before is a string. Here we determine whether it is an empty string. Non-empty strings are implicitly converted to true. The empty string is implicitly converted to false, so the if statement block will no longer be executed. The program will jump to the final return this, and the jQuery object will be returned and the execution will be completed.
           if ( proceed ) {
//proceed a non-empty string and start executing the if statement block. Assume value is "show bd1".
//rnotwhite is a regular expression (/S /g), which means globally matching non-whitespace characters one or more times.
//(value || "") returns "show bd1", which is very simple.
//"show bd1".match((/S /g)) || [] returns ["show", "bd1"]. If you don't know what match does, please check it out.
classes = ( value || "" ).match( rnotwhite ) || [];
//Now classes is ['show', 'bd1'] an array where you want to add the class name.
//Start traversing below and add classes for each DOM object.
                for ( ; i < len; i ) {
//this is the jQuery object, elem is the current DOM object.
                 elem = this[i];
/*
The === operator has a higher priority than the && operator. It first determines whether the DOM node type is an element node.
rclass is a regular expression/[trnf]/g;
The ternary operator in parentheses indicates whether the current DOM node already has a class. If so, the tab character, line feed character, carriage return character, etc. that may exist in the class will be replaced with a string with a space " " , and add a space before and after the current class; if the current DOM node does not have a class, a string with a space " " is also given. Finally it becomes
cur = elem.nodeType === 1 && "show bd1", this is very familiar, yes, it is evaluated according to the first 6 rules.
Assume that the node type of elem is 1, then cur = true && " ", and finally cur = "show bd1".
If the node type of elem is not 1, then cur = false && " ", and finally cur = false.
*/
Cur = elem.nodeType === 1 && ( elem.className ?
                         ( " " elem.className " " ).replace( rclass, " " ):" ");
//Now cur = "show bd1", enter the if statement block for execution.
If ( cur ) {
j = 0;
/*
classes are ["show bd1"]
Loop to check whether the class to be added already exists in the class that the current DOM element already has.
If not, add this class.
*/
While ((Clazz = Classes [J]) {
If ( cur.indexOf( " " clazz " " ) < 0 ) {
                                                                                                                                                                                                                                            cur = clazz " ";
                                                                                                       }                  }
/*
Finally, use $.trim() to remove the space characters at both ends of the class "show bd1".
Check whether the class of the current DOM element is the same as the spliced ​​class. Avoid unnecessary duplication of rendering of the same class.
*/
                           finalValue = jQuery.trim( cur );
If ( elem.className !== finalValue ) {
                                                                                                                                                  to                  }
                }
            }
}
//Return this jQuery object for future chain calls.

return this; }

});

I hope this article will be helpful to everyone’s jQuery programming.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn