jQuery “active” class assignment

风流意气都作罢 提交于 2019-11-30 14:38:02

Assumption: the UL element has the class 'linksList'.

$('.linksList li a').click(function()
{
  $('.linksList li').removeClass('active');
  $(this).parent().addClass('active');
});

Something like the following ought to do it

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

Working Demo

This question is a bit old now, but I think there's still space for improvement.

"Traditional" local event binding:

$("ul a").click(function(){
    $(this).parent("li").addClass("active")
        .siblings().removeClass("active");

    # return false to cancel the default action (e.g. follow the link):
    return false;
});

Now, the same using event delegation via delegate() (jQuery +1.4.2). Lets you dynamically add extra >li>a without having to rebind the event:

$("ul").delegate("a", "click", function(){
    $(this).parent("li").addClass("active")
        .siblings().removeClass("active");

    # return false to cancel the default action
    # and prevent it from bubbling (further) up:
    return false;
});

Change "ul" to anything that matches exclusively the desired list(s), e.g. ".linksList", "#nav", etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!