问题描述
我在SO上看过几篇帖子,但它们在功能和结构方面都太具体了,而我正在寻找的东西是我或任何人都可以在任何地方使用的更通用的东西。
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.
我只需要一个按钮,点击它可以在 3 类之间循环。但是如果出现这种情况需要循环浏览4,5个或更多类,那么脚本可以很容易地缩放。
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');
});
这是一个简单的这个。
现在,你会(好吧,我)认为在方法中添加第三个类会有效,但是它没有:
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');
切换开始发生在 class1 $ c $之间c>和
class3
仅限。
What happens is that the toggling starts happening between class1
and class3
only.
所以这就是我最初的问题:如何拥有切换按钮按顺序循环 3 类?
So this is where I have my initial problem: How to have the Toggle button cycle sequentially through 3 classes?
然后:如果有人需要循环到4,5或更多班级?
And then: What if someone needs to cycle to 4, 5 or more classes?
推荐答案
你可以这样做:
$('.toggle').click(function () {
var classes = ['class1','class2','class3'];
$('div').each(function(){
this.className = classes[($.inArray(this.className, classes)+1)%classes.length];
});
});
这篇关于jQuery:在3个类之间切换(最初)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!