jQuery “active” class assignment

前端 未结 3 1824
我在风中等你
我在风中等你 2021-01-02 21:16

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 l

3条回答
  •  既然无缘
    2021-01-02 22:03

    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.

提交回复
热议问题