javascript - 覆盖 Twitter Bootstrap 3's radio group "onclick“事件

标签 javascript html twitter-bootstrap twitter-bootstrap-3 radio-button

我基本上使用两个单选按钮使用 twitter bootstrap 的 Button Group 组件创建了一个开/关开关。

问题是当我单击“事件”(或“选中”)单选按钮时,我希望开关无论如何都能触发更改。我可以通过 Javascript 执行此操作,但出于某种原因,它会在我的 JS 完成后自动点击返回。

所以基本上我点击,我的 JS 点击另一个标签,然后 Bootsrap 点击它回来。无论如何要覆盖 Bootstraps 行为?

Here is a fiddle


HTML

<div class="btn-group sp_toggle_switch" data-toggle="buttons">
    <label class="btn btn-primary btn-xs">
        <input type="radio" name="display_share_btn" value="true">ON
    </label>      
    <label class="btn btn-default btn-xs">
        <input type="radio" name="display_share_btn" value="false">OFF
    </label>      
</div>   

Javascript

$(document).on('click','.sp_toggle_switch label.active',function(){
  $(this).siblings('label:not(.active)').trigger('click');
});

CSS

.sp_toggle_switch label:not(.active ) {background:#ffffff;  border-color: #ccc;}
.sp_toggle_switch label:not(.active ):hover {background:#f1f1f1;}
.sp_toggle_switch label {text-indent: 99px; overflow: hidden; width: 30px;}
.sp_toggle_switch label.active {text-indent: 0px; width: 36px;}
.sp_toggle_switch.switch_sm label {width: 24px; height: 17px; font-size: 10px; line-height: 14px;}
.sp_toggle_switch.switch_sm label.active {width: 32px; }

最佳答案

哇...出于某种原因,我决心解决这个问题。我昨天做了一点运气,但我想我今天早上掌握了它。我已经在我的环境中使用它,所以希望它对你有用

$('.sp_toggle_switch label').on('click',function(e){

    var parent = $(this).closest('[data-toggle="buttons"]');

    if ( $(this).hasClass('active') ) {

        $(this).find('input:radio').removeAttr('checked');

        parent.find('label').not('.active').find('input:radio').attr('checked', 'checked');
        parent.find('label').not('.active').addClass('active');  

        $(this).removeClass('active');

        e.preventDefault(); // to prevent bootstrap from triggering after class change
        return false;

    } else {

        $(this).find('input:radio').attr('checked', 'checked');
        parent.find('.active').find('input:radio').removeAttr('checked');

        return true;
    }

});

关于javascript - 覆盖 Twitter Bootstrap 3's radio group "onclick“事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086969/

相关文章:

jquery - json 查询字符串中的 URL 格式

jquery - 如何在 Bootstrap 2 中指定工具提示的宽度

javascript - Angular 模块 - 静态解析符号值时遇到错误

javascript - 将 .live() 转换为 .on() 或 .click() 函数 jquery

javascript - 每次点击都带有链接的 jQuery 菜单

javascript - 是否可以使用 Threejs 为立方体的每个面添加不同的颜色

d :h:m:s 的 JavaScript 倒计时

html - 使用下拉菜单进行顶级导航 : have IE bugs

javascript - Shadow DOM 元素可以继承 CSS 吗?

twitter-bootstrap - 面向非设计师的 Zurb Foundation vs Twitter Bootstrap