如何添加类“Active"?单击 li 元素并同时将其从其他元素中删除? [英] How can add class "Active" on click of an li element and remove it from others at the same time?

查看:31
本文介绍了如何添加类“Active"?单击 li 元素并同时将其从其他元素中删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我的菜单是:

    <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>

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

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

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

    });

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

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

推荐答案

试试这个

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

    });

演示

这篇关于如何添加类“Active"?单击 li 元素并同时将其从其他元素中删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆