jQuery“活动”类分配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1262919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:02:28  来源:igfitidea点击:

jQuery "active" class assignment

jquerystatesticky

提问by Russ Cam

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.

很简单,但伙计,我打败了我。

回答by Lior Cohen

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

假设:UL 元素具有“linksList”类。

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

回答by Russ Cam

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

工作演示

回答by Pablo Ziliani

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:

现在,同样通过 delegate() (jQuery +1.4.2) 使用事件委托。让你动态添加额外的 >li>a 而不必重新绑定事件:

$("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.

将“ul”更改为与所需列表完全匹配的任何内容,例如“.linksList”、“#nav”等。