Jquery addclass/removeclass 单击

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

Jquery addclass/removeclass on click

jqueryhtml

提问by Edward

I'm trying to add a class [active] when I click on a element in my menu. Then remove that class [active] when I click on a new item in the menu and add the [active] class to it.

当我单击菜单中的一个元素时,我试图添加一个类 [active]。然后当我单击菜单中的新项目并将 [active] 类添加到它时删除该类 [active]。

I've tried $(this).removeClass("active").addClass("active");

我试过了 $(this).removeClass("active").addClass("active");

$(this).toggleClass("active");

Basically i'm trying to make the hover() function but with the click even.

基本上我正在尝试使悬停()函数但单击甚至。

Edit: Fixed HTML

编辑:固定 HTML

<ul class="menu">
    <li><span>Three</li>
    <li><span>Two</li>
    <li><span>One</li>
</ul>

回答by Alnitak

Assuming only one activeelement at a time and without further knowledge of your DOM hierarchy.

假设一次只有一个active元素,而无需进一步了解 DOM 层次结构。

$('.active').removeClass('active');
$(this).addClass('active');

More efficient options are available if the DOM hierarchy is known.

如果 DOM 层次结构已知,则可以使用更有效的选项。

For example, if they're all siblings, you can use this:

例如,如果他们都是兄弟姐妹,你可以使用这个:

$(this).addClass('active').siblings('.active').removeClass('active');

回答by Coby

DEMO— Working example.

演示- 工作示例。

Corrected your markup:

更正了您的标记:

<ul class="menu">
  <li><span>Three</span></li>
  <li><span>Two</span></li>
  <li><span>One</span></li>
</ul>

Assuming you want the LItags to have the activeclass.

假设您希望LI标签具有active类。

<script>
$('.menu li').on('click', function(){
    $(this).addClass('active').siblings().removeClass('active');
});
</script>

回答by Andrey Ponomarenko

Try this small lib, you can toggle class with native js? It will be like

试试这个小库,你可以用原生js切换类吗?它会像

var menu = document.querySelector('.menu');
menu.addEventListener('click', function () {
  Elemental.toggleClass(this, 'active');
})

it will add or removes class depending on its presence.

它将根据它的存在添加或删除类。