jQuery 如何在单击 li 元素时添加类“Active”并同时将其从其他元素中删除?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20676915/
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-27 01:15:10  来源:igfitidea点击:

How can add class "Active" on click of an li element and remove it from others at the same time?

jquerycss

提问by AppleBud

I am trying to create a menu in which I want to change the CSS of an li element on click while at the same time, CSS of other li's should remain the same.

我正在尝试创建一个菜单,在其中我想在单击时更改 li 元素的 CSS,同时其他 li 的 CSS 应保持不变。

My menu is:

我的菜单是:

    <ul id="menu">
    <li><a href="#">Parent 1</a> </li>
    <li><a href="#">item 1</a></li>
    <li><a href="#">non-link item</a></li>
    <li><a href="#">Parent 2</a> </li>
</ul>

and my jquery to add CSS to the selected element is:

和我的 jquery 添加 CSS 到所选元素是:

 $("#menu li a").click(function() {
    $(this).parent().addClass('selected');

    });

However, right now, I am unable to remove the added CSS from a non-selected element. Is there anyway I can implement this?

但是,现在,我无法从未选择的元素中删除添加的 CSS。无论如何我可以实现这个吗?

回答by Sridhar R

Try this

尝试这个

$("#menu li a").click(function() {
    $(this).parent().addClass('selected').siblings().removeClass('selected');

    });

DEMO

演示

回答by Sowmya

Try this

尝试这个

$("#menu li a").click(function() {
  $("#menu li").removeClass('selected');
    $(this).parent().addClass('selected');
});

DEMO

演示

回答by Wannes

Try this, this will always work

试试这个,这将永远有效

$("#menu li a").on('click', function(e){
    $("#menu .active").removeClass('active');
    $(this).parent().addClass('active'); 
    e.preventDefault();
});

回答by Jan Drewniak

Or for the javascript-free approach, you can use radio buttons:

或者对于 javascript-free 方法,您可以使用单选按钮:

http://www.onextrapixel.com/2013/07/31/creating-content-tabs-with-pure-css/

http://www.onextrapixel.com/2013/07/31/creating-content-tabs-with-pure-css/

and use the sibling selector to style them

并使用兄弟选择器来设置它们的样式

input[type='radio']:checked + label

DEMO

演示

回答by Dhaval Marthak

You can target the .siblings()

您可以针对 .siblings()

$("#menu li a").click(function() {
    $(this).parent().addClass('selected').siblings().removeClass('selected');
});

回答by Hiral

$("#menu li a").click(function(){
    // Remove active if this does not have active class
    if(!($(this).closest("li").hasClass("active"))){
        $(this).closest("#menu").find("li.active").removeClass('selected');
    }
    $(this).closest("li").addClass('selected');
});