我基本上使用两个单选按钮使用 twitter bootstrap 的 Button Group 组件创建了一个开/关开关。
问题是当我单击“事件”(或“选中”)单选按钮时,我希望开关无论如何都能触发更改。我可以通过 Javascript 执行此操作,但出于某种原因,它会在我的 JS 完成后自动点击返回。
所以基本上我点击,我的 JS 点击另一个标签,然后 Bootsrap 点击它回来。无论如何要覆盖 Bootstraps 行为?
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/