最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavascriptJQuery Toggle Active Class between 2 buttons on a button group - Stack Overflow

programmeradmin4浏览0评论

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>

Button 2 it already active.

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?

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>

Button 2 it already active.

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?

Share Improve this question edited May 2, 2018 at 2:13 Ricardo 4,3085 gold badges42 silver badges58 bronze badges asked Apr 2, 2017 at 14:25 user7801216user7801216
Add a ment  | 

1 Answer 1

Reset to default 13

Use:

$('.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.

Here's a working snippet:

$('.btn-group').on('click', '.btn', function() {
  $(this).addClass('active').siblings().removeClass('active');
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn./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>

发布评论

评论列表(0)

  1. 暂无评论