Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

jquery - toggleClass and remove class from all other elements

How can I toggleClass and remove class from all other elements? Consider a div that contains a tags: html:

<div class="size">
   <a href="">blahblah</a>
   <a href="">blahblah</a>
</div>

jQuery:

 $(".size a").click(function(){
 $(this).toggleClass('checked');
 if($(".size a").hasClass('checked')){
     $(this).removeClass('checked');
  }
 })

I want to add class "cheched" to element and remove the class "ckeched" from other elements that have class "checked" . My code remove all classes. How can I add specific class and remove other element's class with click? Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will do it

 $(".size a").click(function(){
    $('.size a.checked').not(this).removeClass('checked');
    $(this).toggleClass('checked');
 })

Update

Alternatively you could do

 $(".size").on('click','a', function(){
    $(this).toggleClass('checked').siblings().removeClass('checked');
 })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...