How to toggle a specific class on an element where

2019-08-28 06:07发布

问题:

I have an element that has multiple classes. I would like to just switch between one of the classes when I click it.

<span class="icon-expand desktop-only mt8 pl4" id="toggle-site-content-width"></span>

When I click this, I need to just change icon-expand into icon-reduce, and just leave the other classes as is.

It just adds the class at the end when I'm using $(this).toggleClass('icon-reduce'). Same happens when I'm doing this: $(this).toggleClass('icon-expand','icon-reduce').

This is the full code:

$(function(){
    $('#toggle-site-content-width').click(function(){  //  on click
        $('#site-content').children('div').toggleClass('content-align-center');  //  remove this class to expand the view to full available window width
        $(this).toggleClass('toggle-expand','icon-reduce');  //  change the icon
        $(this).trigger('resize');  //  trigger the window to rearrange masonry bricks
    });
});

回答1:

You need to change:

$(this).toggleClass('toggle-expand','icon-reduce');  

to:

$(this).toggleClass('toggle-expand icon-reduce');

You don't need to separate your classes by , here.