切换按钮组中的类 [英] Toggling class in group of buttons
问题描述
我有一组按钮的以下标记:
I have the following markup for a group of buttons:
<div class="btn-group pull-right">
<button type="button" class="btn btn-default" id="today">Today</button>
<button type="button" class="btn btn-default" id="this_week">This Week</button>
<button type="button" class="btn btn-default" id="this_month">This Month</button>
<button type="button" class="btn btn-default" id="custom">Custom</button>
</div>
我正在尝试更换类 btn-default
使用jQuery在按钮上使用类 btn-primary
,这样点击时,单击的按钮将具有以下 class =btn btn-primary
,以及类 btn-primary
组中的任何其他按钮将切换回 btn-default
。
I'm trying to replace class btn-default
with class btn-primary
on the button using jQuery so that when clicked, the clicked button will have the following class="btn btn-primary"
, and any other button in the group with class btn-primary
will toggle back to btn-default
.
对于我在下面提供的内容,是否有更优雅的解决方案?我是否必须为每个按钮编写一个功能?此外,我冒险将btn btn-default
添加到已有该类的按钮。非常感谢任何帮助。
Is there a more elegant solution to what I have provided below? Do I have to write a function for every button? Also, I risk adding btn btn-default
to a button which already has that class. Any help is greatly appreciated.
$("#today").click(function () {
$(this).parent().find("btn btn-primary").removeClass("btn btn-primary");
$(this).parent().addClass("btn btn-default");
$(this).addClass("btn btn-primary");
});
推荐答案
$('.btn-group').on('click', '.btn', function() {
$(this).addClass('btn-primary').siblings().removeClass('btn-primary').addClass('btn-default');
});
.btn-default {
color: red;
}
.btn-primary {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="btn-group pull-right">
<button type="button" class="btn btn-default" id="today">Today</button>
<button type="button" class="btn btn-default" id="this_week">This Week</button>
<button type="button" class="btn btn-default" id="this_month">This Month</button>
<button type="button" class="btn btn-default" id="custom">Custom</button>
</div>
-
$(this)
:是按钮点击 -
addClass('btn-primary')
:将指定的类添加到单击的按钮 -
.siblings('。btn')
:将获得btn
类的兄弟姐妹(同一级别的节点)此
元素 -
.removeClass('btn-primary')。addClass('btn-default' )
:相应更新类兄弟姐妹
$(this)
: is the button that is clickedaddClass('btn-primary')
: Adds specified class to the clicked button.siblings('.btn')
: will get the siblings(nodes on same level) havingbtn
class ofthis
element.removeClass('btn-primary').addClass('btn-default')
: Update classes accordingly ofsiblings
这篇关于切换按钮组中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!