Try the following:
var classNames = ['mute','on','off']; $('div').click(function () { $(this).toggleClass(function (i, className, b) { var index = (classNames.indexOf(className) + 1) % classNames.length; $(this).removeClass(className); return classNames[index]; }); });
In this code className is the old class. Then get the new class through the classNames array, and then return it.
And before returning, the old class must be deleted.
And with this method, you can easily expand from 3 to any larger number .
Here is the jsfiddle. http://jsfiddle.net/f3qR3/2/
Another situation
If the element has other classes, you can use the following code, but it is more complicated.
var classNames = ['mute', 'on', 'off']; $('div').click(function () { var $this = $(this); $this.toggleClass(function (i, className, b) { var ret_index; $.each(classNames, function (index, value) { if ($this.hasClass(value)) { ret_index = (index + 1) % classNames.length; } }); $this.removeClass(classNames.join(' ')); return classNames[ret_index]; }); });
Here is the jsfiddle. http://jsfiddle.net/f3qR3/4/
source share