简体   繁体   中英

Add/Remove classes using jQuery

I have few tabs defined and wrapper around a tag. They contain several elements like spans, img etc. My idea is to add class ACTIVE for clicked tab and remove it from previous tab so that only one is active at any point of time. The code I use is working

     <script>
     $(document).ready(function() {
         $(".tabs").click(function() {
            $(this).toggleClass("active");

         });
     });

But this is just part of solution. Its adding class to tab but it does not remove it from previous clicked tab. So if I have 3 tabs and click on each, all will be selected. Any easy fix for this?

$(".tabs").click(function() {
     $(".tabs").removeClass("active");
     $(this).addClass("active");
});

You can also try this

$(".tabs").on('click',function() {
   $(".tabs").removeClass("active");
   $(this).addClass("active");
});

About on: Attach an event handler function for one or more events to the selected elements.

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