4

我有 3 张图像要在它们之间切换。我将它们中的每一个放在一个类中并在 css 中更改它的图像。我现在可以在 2 个类之间切换,但是当我添加第三个类时,代码不起作用。他们中的任何一个班级都可以成为起始班级。

    $('.one').click(function(){                             
        $(this).toggleClass("two");
        $(this).toggleClass("one");

    });
     $('.two').click(function(){                             
        $(this).toggleClass("one");
        $(this).toggleClass("two");

    });

当我添加这一行时:

        $(this).toggleClass("three"); 

根本不切换....

你知道我可以把它们都放在一个函数中的方法吗?

谢谢。

4

3 回答 3

14

小提琴示例:http: //jsfiddle.net/KdfEV/

此代码将允许您循环浏览一系列已定义的类

$('.one, .two, .three').click(function() {                             
    this.className = {
       three : 'one', one: 'two', two: 'three'
    }[this.className];
});
于 2012-06-05T09:09:34.460 回答
4
$('.one, .two, .three').click(function(){                             
        $(this).toggleClass("one, two, three");
    });
于 2012-06-05T08:54:17.907 回答
0

最安全的方法是删除不需要的类并添加所需的类:

// Switch to class 'three'
$(this).removeClass('one').removeClass('two').addClass('three');
于 2012-06-05T08:54:27.313 回答