简体   繁体   中英

Three way toggle to add and remove classes in jQuery

I'm trying to get multiple divs with the class 'box' to switch between three classes: 'box', 'box black', and 'box blue' when I click on them. Something isn't quite working with how I have it set up. Thanks for your help!

$('.box').click(function () {
    if ($(this).class == 'box') {
        $(this).addClass('black');
    } else if ($(this).class == 'box black') {
        $(this).removeClass('black');
        $(this).addClass('blue');
    } else if ($(this).class == 'box blue') {
        $(this).removeClass('blue');
    }
});

Your element always has the class .box so it will always trigger the initial condition. Try added a secondary initial class like this: DEMO

HTML

<div class="box none"></div>

jQuery

    $('.box').click(function () {
        if ($(this).hasClass('none')) {
            $(this).removeClass('none');
            $(this).addClass('black');
        } else if ($(this).hasClass('black')) {
            $(this).removeClass('black');
            $(this).addClass('blue');
        } else if ($(this).hasClass('blue')) {
            $(this).removeClass('blue');
            $(this).addClass('none');
        }
    });

CSS

   .box {
        border: solid 1px;
        width: 100px;
        height: 100px;
        background: #fff;
    }

    .black {
        background: #000;
    }
    .blue {
        background: blue;
    }

Try

$('.box').click(function () {
    if ($(this).hasClass('box')) {
        if ($(this).hasClass('black')) {
            $(this).removeClass('black').addClass('blue');
        } else if ($(this).hasClass('blue')) {
            $(this).removeClass('blue');
        } else {
            $(this).addClass('black');
        }
    }
});

First you check if the element has class box. If so, you toggle between the second classes (black, blue an no class).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM