在两个不同的类之间切换jQuery [英] Switching between two different classes jQuery

查看:113
本文介绍了在两个不同的类之间切换jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法获取以下代码工作:

Having trouble getting the following code to work:

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

我无法得到它切换以下div的类。

I cannot get it to switch the following div's class.

<div id="playfield" class="gridView"></div>

有任何想法吗?

尝试这样:

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

看起来工作正常,什么原因?

And it seems to work fine, what the heck?

推荐答案

我不知道switchClass,也许你在想toggleClass?无论如何 - 我有一些旧的代码使用这个(我有一些奇怪的问题与toggleClass):

I wasn't aware of a switchClass, perhaps you were thinking of toggleClass? Anyways - I had some old code that used this (I was having some strange issues with 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应该可以满足您的需求。

But as others have suggested toggleClass should work for your needs.

这篇关于在两个不同的类之间切换jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆