jQuery “active” class assignment

2019-02-09 21:41发布

All I am trying to accomplish is to be able to have an unordered list of links in which one is clicked, the parent list item is assigned the class "active." Once another link is clicked within that list, it checked to see if "active" is assigned, remove it from that list item, and add it to the most recent clicked links parent list item.

Example:

Step One - User has clicked the link "I am link two"

<ul>
<li><a href="#">I am link one</a></li>
<li class="active"><a href="#">I am link two</a></li>
</ul>

Step Two - User has now clicked the link "I am link one"

<ul>
<li class="active"><a href="#">I am link one</a></li>
<li><a href="#">I am link two</a></li>
</ul>

Pretty simple, but man I beat me up.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-02-09 22:05

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

查看更多
乱世女痞
3楼-- · 2019-02-09 22:10

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.

查看更多
Animai°情兽
4楼-- · 2019-02-09 22:22

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

$('.linksList li a').click(function()
{
  $('.linksList li').removeClass('active');
  $(this).parent().addClass('active');
});
查看更多
登录 后发表回答