Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - jQuery: Toggling between 3 classes (initially)

I've seen several posts here on SO but they are too specific in functionality and structure, and what I'm looking for is something more universal that I or anyone can use anywhere.

All I need is to have a button that when clicked can cycle between 3 classes. But if the case arises to have to cycle through 4, 5 or more classes, that the script can be easily scaled.

As of this moment I am able to 'cycle' between two classes which is basically more "toggling" than cycling, so for that I have:

HTML:

<a href="#" class="toggle">Toggle classes</a>
<div class="class1">...</div>

jQuery:

$('.toggle').click(function () {
  $('div').toggleClass('class1 class2');
});

Here's a simple fiddle of this.

Now, you would (well, I) think that adding a third class to the method would work, but it doesn't:

$('div').toggleClass('class1 class2 class3');

What happens is that the toggling starts happening between class1 and class3 only.

So this is where I have my initial problem: How to have the Toggle button cycle sequentially through 3 classes?

And then: What if someone needs to cycle to 4, 5 or more classes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this :

$('.toggle').click(function () {
  var classes = ['class1','class2','class3'];
  $('div').each(function(){
    this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
  });
});

Demonstration


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...