简体   繁体   中英

JQuery toggle and remove css classes

I have the following CSS:

.red {background-color: #CC0000;}
.green {background-color: #009900;}

and my HTML is:

div class="red" id="ch1">Content</div>
<div class="red" id="ch2">Content</div>
<div class="red" id="ch3">Content</div>
...
<div class="green" id="ch..">Content</div>
<div class="red" id="ch..">Content</div>

and I am using the following script to change class on divs:

$(document).ready(function() { 
$(".red , .green").click(function(){
    $(".green").removeClass("green").addClass("red");
     $(this).toggleClass('red green');
});   
});

Works fine to change div class onclick from .red to .green but when I click on the "green" the div doesn't becomes "red". I other words I would like to have or all "red" or just ONE "green" div ALSO nothing is working if I change the sequence of .red - .green in my CSS

Any thoughts? Thanks in advance

不要包含被点击的元素...

$(".green").not(this).removeClass("green").addClass("red");

Only using toggleClass() should work. So remove following line from your code $(".green").removeClass("green").addClass("red");

Solution:-

$(document).ready(function() { 
    $(".red , .green").click(function(){
        $(this).toggleClass('red green');
    });   
});

Is this what you are expecting? http://jsfiddle.net/k23g3ne4/

this is working :

$(this).siblings('.red , .green')
  .removeClass("green")
  .addClass("red");

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