Fixing some bugs in the re-tooling of toggleClass, adding in some performance optimizations.

This commit is contained in:
jeresig 2010-01-06 15:23:30 -05:00
parent 600d314538
commit 2526e29353

View file

@ -93,26 +93,27 @@ jQuery.fn.extend({
return this; return this;
}, },
toggleClass: function( classNames, state ) { toggleClass: function( value, stateVal ) {
var type = typeof classNames; var type = typeof value, isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( classNames ) ) { if ( jQuery.isFunction( value ) ) {
return this.each(function(i) { return this.each(function(i) {
var self = jQuery(this); var self = jQuery(this);
self.toggleClass( classNames.call(this, i, self.attr("class")), state ); self.toggleClass( value.call(this, i, self.attr("class")), stateVal );
}); });
} }
return this.each(function(){ return this.each(function() {
if ( type === "string" ) { if ( type === "string" ) {
// toggle individual class names // toggle individual class names
var isBool = typeof state === "boolean", className, i = 0, var className, i = 0, self = jQuery(this),
classNames = classNames.split( rspace ); state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) { while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list // check each className given, space seperated list
state = isBool ? state : !jQuery(this).hasClass( className ); state = isBool ? state : !self.hasClass( className );
jQuery(this)[ state ? "addClass" : "removeClass" ]( className ); self[ state ? "addClass" : "removeClass" ]( className );
} }
} else if ( type === "undefined" || type === "boolean" ) { } else if ( type === "undefined" || type === "boolean" ) {
@ -122,7 +123,7 @@ jQuery.fn.extend({
} }
// toggle whole className // toggle whole className
this.className = this.className || classNames === false ? "" : jQuery.data( this, "__className__" ) || ""; this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
} }
}); });
}, },