Question about jQuery source code (addClass)

Can you explain the following logic inside "if (jQuery.isFunction (value))" inside addClass? I don’t understand what his purpose is. Thanks.

addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, 
+6
source share
5 answers

Take a look at the API page. You will see that there is a way to call addClass , which passes the function as the first argument. The function receives the element and returns the names of the classes to be added:

A function that returns one or more class names, separated by spaces, to be added. Gets the index position of the element in the set and the value of the old class as arguments. Inside the function, this refers to the current element in the set.

So you can do this:

 $('.someElements').addClass(function(i, currentClass) { return 'newClass' + i; }); 

In the first selected element, the class newClass0 will be added, the second newClass1 , etc.


With the code you sent:

 if (jQuery.isFunction(value)) { return this.each(function (j) { jQuery(this).addClass(value.call(this, j, this.className)); }); } 

It says:

  • If the first argument was a function
  • Scrolling through all selected items
  • For each of them, call a function with the element as context ( this value), position in the loop as the first argument and the className property as the second argument).
  • Then call the addClass method with the result of step # 3.
+12
source

Take a look at the documentation, there may be a function inside.

.addClass (function (index, currentClass)) Function (index, currentClass) A function that returns one or more classes, space-separated names to add. Gets the index position of the element in set and the old class value as arguments. Inside a function, this refers to the current element in the set.

0
source

This is explained in the API . It is used to check if the argument passed is a function that returns a list of space-separated classes.

0
source

You can use the function in .addClass (), for example:

 $(document).ready(function() { $("li").addClass(function(i) { return "li" + i; }); }); 
0
source

Try

  function addClass(elem, className) { if (!hasClass(elem, className)) { elem.className += ' ' + className; } } 
-1
source

Source: https://habr.com/ru/post/897225/


All Articles