简体   繁体   中英

remove and addClass only works once

I'm developing a menu that has two modes, when the user clicks on one of them the class of a list item changes, I can get it to work at the first mode change but when I try to change back it does not work.

this is my code

$('#menu ul.mode li.edit').click(function() {
    $('#menu').css('background-image', 'url(images/edit-menu/fundo.png)');
    });
    $('#menu ul.icons li.ummix').removeClass('ummix').addClass('um');


$('#menu ul.mode li.mix').click(function() {
    $('#menu').css('background-image', 'url(images/edit-menu/fundo-mix.gif)');
    $('li.um').removeClass('um').addClass('ummix');

});

the part that doesn't work is

$('#menu ul.icons li.ummix').removeClass('ummix').addClass('um');

My HTML is like this

<div id="menu">
<ul class="mode">
    <li class="edit"><a href="#edit"><img src="images/edit-menu/selected/edit.gif" /></a></li>
    <li class="mix"><a href="#mix"><img src="images/edit-menu/icons/mix.png" /></a></li>
</ul>

<ul class="icons"> 
    <li class="um"></li>
</ul>

Adding and removing opposite classes becomes unwieldy.

Assuming that unmix and um are opposites of one another, I would encourage you to use just one class. Then check for its existence or nonexistence. At that point you could simply use something like toggleClass() .

After you remove the ummix class, the selector no longer applies to those elements. Try adding the um class before removing the ummix one.

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