Add & remove active class from a navigation link

前端 未结 4 441
有刺的猬
有刺的猬 2020-12-18 03:50

I have been looking for tutorials on how to add and remove a class from a link unfortunately without any success. All the earlier questions on this have give me some underst

4条回答
  •  有刺的猬
    2020-12-18 04:51

    Try:

    $(function() {
        $('li a').click(function(e) {
            e.preventDefault();
            var $this = $(this);
            $this.closest('ul').find('.active').removeClass('active');
            $this.parent().addClass('active');
    
        });
    });
    

    Your selector was looking at the parent element of the current ($(this)) a element, and then looking among the children of that element for an a. The only a in that element is the one you just clicked.

    My solution instead moves up to the closest ul and then finds the element that currently has the class ofactive` and then removes that class.

    Also your approach, as posted, was adding the active class-name to the li element, and you were looking to remove the class-name from an a element. My approach uses the li, but that can be amended to use the a by simply removing the parent() from the final line.

    References:

    • children().
    • closest().
    • find().

提交回复
热议问题