jQuery - Add active class and remove active from other element on click

前端 未结 6 2224
独厮守ぢ
独厮守ぢ 2020-12-14 09:24

I\'m new to jQuery, so I\'m sorry if this is a silly question. But I\'ve been looking through Stack Overflow and I can find things that half work, I just can\'t get it to f

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 10:08

    Try this

    $(document).ready(function() {
    $(".tab").click(function () {
        $(".tab").removeClass("active");
        // $(".tab").addClass("active"); // instead of this do the below 
        $(this).addClass("active");   
    });
    });
    

    when you are using $(".tab").addClass("active");, it targets all the elements with class name .tab. Instead when you use this it looks for the element which has an event, in your case the element which is clicked.

    Hope this helps you.

提交回复
热议问题