Toggle between 3 classes using toggleclass

▼魔方 西西 提交于 2019-11-28 01:26:45

问题


I have 3 images that I want to switch between. I put each one of them in a class & change it's image in the css. I can now switch between 2 classes but when I add the third one the code doesn't work. Any class of them can be the starting one.

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

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

    });

When I add this line:

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

It doesn't toggle at all....

Do you know a method in which I can put all of them in one function ?

Thanks.


回答1:


Example fiddle: http://jsfiddle.net/KdfEV/

This code will allow you to cycle through a sequence of defined classes

$('.one, .two, .three').click(function() {                             
    this.className = {
       three : 'one', one: 'two', two: 'three'
    }[this.className];
});



回答2:


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



回答3:


The safest way would be to remove unwanted classes and add the required class:

// Switch to class 'three'
$(this).removeClass('one').removeClass('two').addClass('three');


来源:https://stackoverflow.com/questions/10894250/toggle-between-3-classes-using-toggleclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!