首页 > 解决方案 > Bootstrap 单选按钮在选择时会发生变化

问题描述

我使用此 Bootstrap 3 代码将收音机更改为按钮:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="sim_type" value="option 1" checked>Option 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="sim_type" value="option 2">Option 2
    </label>
</div>

它在 jsfiddle 中运行良好,但在我的网站中,单击时按钮的颜色不会改变。它总是这样:

在此处输入图像描述

但是提交的值是正确的。

标签: twitter-bootstrap-3radio-button

解决方案


我添加了这段代码来手动添加 .active 类:

// Change the color of selected radio button
$('label.btn').click(function() {
     $(this).parent('.btn-group').children('label.btn').addClass('active');
     $(this).removeClass('active');
});

更新: 不需要此代码。您最初只需要将“活动”类添加到标签之一。此代码在没有任何 js 的情况下运行良好:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary active">
        <input type="radio" name="sim_type" value="option 1" checked>Option 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="sim_type" value="option 2">Option 2
    </label>
</div>

推荐阅读