Question about jQuery source code (addClass)
Can you explain the following logic inside "if ( jQuery.isFunction( value ))" inside addClass? I don't understand what its purpose. 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 {
setClas开发者_运维问答s = " " + 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;
},
Have a look at the API page. You'll see that there is a way of calling addClass
that passes a function as the first argument. The function receives the element and returns class names to be added:
A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments. Within the function,
this
refers to the current element in the set.
So you can do this:
$('.someElements').addClass(function(i, currentClass) {
return 'newClass' + i;
});
The first element selected will have the class newClass0
added, the second newClass1
, etc.
With the code you posted:
if (jQuery.isFunction(value)) {
return this.each(function (j) {
jQuery(this).addClass(value.call(this, j, this.className));
});
}
This says:
- If the first argument was a function
- Loop through all the elements selected
- For each of them, call the function with the element as the context (the
this
value), the position in the loop as the first argument and theclassName
property as the second argument). - Then call the
addClass
method with the result of step #3.
Take a look at documentation, there can be a function inside.
.addClass( function(index, currentClass) ) function(index, currentClass)A function returning one or more space-separated class names to be added. Receives the index position of the element in the set and the old class value as arguments. Within the function, this refers to the current element in the set.
It's explained in the API. It is used to test if the passed argument is a function that returns a space separated list of classes
You can use function in .addClass() function like:
$(document).ready(function() {
$("li").addClass(function(i) {
return "li" + i;
});
});
Try this
function addClass(elem, className) {
if (!hasClass(elem, className)) {
elem.className += ' ' + className;
}
}
精彩评论