简体   繁体   English

如何将 class 添加到单击的按钮并删除 class 到先前单击的按钮

[英]How to add class to the clicked button and remove a class to the previously clicked button

How will I add a class to the clicked button and remove a class to the previously clicked button.如何将 class 添加到单击的按钮,并将 class 删除到先前单击的按钮。 I want to have a single active button only per click我只想每次点击有一个活动按钮

My html looks like this我的 html 看起来像这样

<div class="nav-button">
   <button id="btn-all">All</button>
   <button id="btn-chicken">Chicken</button>
   <button id="btn-pizza">Pizza</button>
   <button id="btn-pasta">Pasta</button>
   <button id="btn-drinks">Drinks</button>
</div>

And my jquery looks like this而我的 jquery 看起来像这样

$('.nav-button button').on('click', function(){
     $(this).addClass("active")
})

I dont want to select the buttons one by one because this group of button is dynamic.我不想 select 按钮一个接一个,因为这组按钮是动态的。 I just only use the html example above to show my buttons in html我只使用上面的 html 示例在 html 中显示我的按钮

You can simply first remove the class from all buttons:您可以简单地首先从所有按钮中删除 class:

 $("div.nav-button button").removeClass('active');

So you can do:所以你可以这样做:

 $('.nav-button button').on('click', function(){ $("div.nav-button button").removeClass('active'); $(this).addClass("active"); })
 .active { background-color: yellow; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="nav-button"> <button id="btn-all">All</button> <button id="btn-chicken">Chicken</button> <button id="btn-pizza">Pizza</button> <button id="btn-pasta">Pasta</button> <button id="btn-drinks">Drinks</button> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为按钮添加样式并删除先前单击的按钮的样式? - How to add style to button and remove style of previously clicked button? 单击按钮时如何删除行并添加CSS类 - how to remove row and add css class when button clicked 将 class 添加到单击按钮 if 语句 - Add class to clicked button if statement 为单击的按钮添加 class 并从兄弟姐妹中删除 class - Add class for the clicked button and remove class from siblings 如何在单击按钮时添加css类,以及如何通过单击另一个按钮将其删除 - how to add a css class when button clicked and and also remove that with another button click 如何将类别添加到单选按钮组中未单击的单选按钮 - How to add class to not clicked radio button in radio button group 如果在子按钮上将“活动”类添加到“此”父级,则单击该按钮并在再次单击按钮时切换“活动”类 - How to add “active” class to “this” parent on child button is clicked and toggle “active” class if button clicked again 我想删除以前使用普通javascript单击的按钮上的`active`类 - I want to remove the `active` class on the button which was previously clicked using vanilla javascript 单击提交按钮后删除课程 - Remove class after submit button is clicked 单击按钮时删除类的所有实例 - Remove all instances of class when button clicked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM