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

前端 未结 6 2223
独厮守ぢ
独厮守ぢ 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:10

    You can remove class active from all .tab and use $(this) to target current clicked .tab:

    $(document).ready(function() {
        $(".tab").click(function () {
            $(".tab").removeClass("active");
            $(this).addClass("active");     
        });
    });
    

    Your code won't work because after removing class active from all .tab, you also add class active to all .tab again. So you need to use $(this) instead of $('.tab') to add the class active only to the clicked .tab anchor

    Updated Fiddle

提交回复
热议问题