Javascript / JQuery在按钮组的2个按钮之间切换活动类 [英] Javascript / JQuery Toggle Active Class between 2 buttons on a button group
本文介绍了Javascript / JQuery在按钮组的2个按钮之间切换活动类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 btn-group
中使用bootstrap。有html:
I am using bootstrap with btn-group
. There is the html:
<div class="btn-group btn-group-sm" role="group">
<div type="button" class="btn btn-default btn-1">Button 1</div>
<div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div>
按钮2它已经激活。
目前我这样做是为了从一个中移除活动类并将其添加到另一个。
Currently I'm doing this to remove the active class from one and add it to another.
$('.btn-2').removeClass('active');
$('.btn-1').addClass('active');
这是最干净的方法吗?还是有更好的方法可以切换这个活跃的两个按钮之间的类?
Is this the cleanest way to do this or is there a better way so it can just toggle this active class between the two buttons?
推荐答案
使用:
$('.btn-group').on('click', '.btn', function() {
$(this).addClass('active').siblings().removeClass('active');
});
我认为代码是不言自明的?它只是从您单击的按钮的兄弟中删除任何现有的活动类,并将该类添加到单击的按钮。
I think the code is fairly self-explanatory? It simply removes any existing "active" classes from the siblings of the button you clicked, and adds that class to the clicked button.
这是一个工作片段:
$('.btn-group').on('click', '.btn', function() {
$(this).addClass('active').siblings().removeClass('active');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="btn-group btn-group-sm" role="group">
<div type="button" class="btn btn-default btn-1">Button 1</div>
<div type="button" class="btn btn-default btn-2 active">Button 2</div>
</div>
这篇关于Javascript / JQuery在按钮组的2个按钮之间切换活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文