[英]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.