Напишите функцию для генерации обратных вызовов:
var click = 0; // keep track of how many times user has clicked
// Generates an event handler that will remove oldClass, add newClass, increment
// click, and update the element text whenever it is called.
function ClassSwapper(oldClass, newClass)
{
return function()
{
$(this)
.removeClass(oldClass)
.addClass(newClass)
.html('No. of clicks: ' + ++click);
};
}
// generate three event handlers for toggle, such that the three
// format classes are cycled.
$('#div-toggle').toggle(
ClassSwapper('format3', 'format1'),
ClassSwapper('format1', 'format2'),
ClassSwapper('format2', 'format3')
);
Обратите внимание, что toggle()
вращает обработчики от последнего к первому, поэтому вы, вероятно, хотите, чтобы ваш первый обработчик удалил класс, добавленный последним ...
Поскольку у вас есть счетчик, вы можете просто полностью избежать toggle()
и объединить счетчик, список классов для циклического перехода и обработчик события click
:
// number of times user has clicked, and also index of *next* class to use
var click = 0;
$("#div-toggle").click(function()
{
// classes to cycle through
var classes = ['format1', 'format2', 'format3'];
// removes previous class, adds new one.
// note that, for brevity, this takes advantage of
// a detail specific to JavaScript arrays: negative indexes are
// interpreted as property names, so the first time this is called,
// removeClass() will be passed the value of classes["-1"] (which will
// return undefined) and will as a result do nothing.
$(this)
.removeClass(classes[(click-1)%classes.length])
.addClass(classes[(click)%classes.length])
.html('No. of clicks: ' + ++click);
});