在两个不同的类jQuery之间切换

无法获得以下代码:

$('#changeMode').button().click(function(){ $('#playfield').toggle(function() { $(this).switchClass("gridView","plainView"); }, function() { $(this).switchClass("plainView","gridView"); }); }); 

我无法让它切换下面的div类。

 

有任何想法吗?

编辑:我试过这个:

 $('#changeMode').button().click(function(){ if ($('#playfield').attr('class') == "gridView"){ $('#playfield').removeClass("gridView"); $('#playfield').addClass("plainView"); } else { $('#playfield').removeClass("plainView"); $('#playfield').addClass("gridView"); } }); 

它似乎工作正常,到底是什么?

我不知道switchClass,也许你在考虑toggleClass? 无论如何 – 我有一些使用它的旧代码(我在toggleClass中遇到了一些奇怪的问题):

 $(this).removeClass("gridView").addClass("plainView"); or $(this).toggleClass("gridView plainView"); 

反之亦然。

例:

 $('#changeMode').button().click(function(){ $('#playfield').toggle(function() { $(this).toggleClass("gridView plainView"); //$(this).removeClass("gridView").addClass("plainView"); }, function() { $(this).toggleClass("plainView gridView"); //$(this).removeClass("plainView").addClass("gridView"); }); }); 

但正如其他人所说,toggleClass应该适合您的需求。

正确的语法是在第一个参数中使用“一个或多个类名( 由空格分隔 )..”(来自.toggleClass() ),而不是在第一个和第二个参数中引用类名。

例如

 $(this).toggleClass("gridView plainView"); 

只需使用两次toggleClass即可。 toggoleClass引用Jquery
This method takes one or more class names as its parameter. In the first version, if an element in the matched set of elements already has the class, then it is removed; if an element does not have the class, then it is added.

至于你的问题。

$('#changeMode').button().click(function(){ $(this).toggleClass('gridView').toggleClass('plainView'); });

帮助这将解决你的问题。

@Guy toggleClass('gridView plainView')这实际上是替代之间的替代

and

.

而不是在两个classe之间切换。 没有恶意 。 希望这会有所帮助。

jQuery还有一个toggleClass API:

http://api.jquery.com/toggleClass/

这就像Rionmonster建议的那样,在没有设置类时添加类,并在已经设置时删除它们。