嗨,我正在使用Bootstrap的.btn组类,如下所示:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" name="radio-popup-position" id="radio-popup-style-1" checked>button-1
</label>
<label class="btn btn-default">
<input type="radio" name="radio-popup-position" id="radio-popup-style-2">button-2
</label>
<label class="btn btn-default">
<input type="radio" name="radio-popup-position" id="radio-popup-style-3">button-3
</label>
<label class="btn btn-default">
<input type="radio" name="radio-popup-position" id="radio-popup-style-4">button-4
</label>
在我的应用程序中,我需要用JS"手动"选择一个按钮,目前我是这样做的:
$('#radio-popup-style-rect-1').parent().addClass('active');
$('#radio-popup-style-rect-1').get(0).checked = true;
$('#radio-popup-style-rect-2').removeAttr('checked').parent().removeClass('active');
$('#radio-popup-style-rect-3').removeAttr('checked').parent().removeClass('active');
$('#radio-popup-style-rect-4').removeAttr('checked').parent().removeClass('active');
四次,对于每种情况,我都需要选择其中一个按钮。如果我只有4个按钮,那没什么大不了的,但现在我需要13个。这意味着很多代码。
我的问题-Bootstrap是否有一个功能,我可以调用它来选择一个按钮,并自动取消选择同一组中的其他按钮?
干杯
您可以使用属性选择器
$('[id*="radio-popup-style-"]').click(function(){
$(this).prop('checked', true).parent().addClass('active');
$('[id*="radio-popup-style-"]').not($(this)).removeAttr('checked').prop('checked', false).parent().removeClass('active');
});
JSFIDDLE:http://jsfiddle.net/TRNCFRMCN/6o1k1cvo/1/.
关于属性选择器中的regex:http://www.thegeekyway.com/css-regex-selector-using-regular-expression-css/.
您可以使用内置BS方法来切换按钮状态:
(您需要页面上的默认按钮.js)
https://github.com/twbs/bootstrap/blob/master/js/button.js#L52-L66http://getbootstrap.com/javascript/#buttons
$('#the-button-id-you-need').button('toggle');
没有这样的函数/方法。然而,这是没有必要的。
使用class
属性而不是id
。然后代码变得简单多了:
HTML:
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default active">
<input type="radio" name="radio-popup-position" class="radio-popup-style" checked>button-1
</label>
<label class="btn btn-default">
<input type="radio" name="radio-popup-position" class="radio-popup-style">button-2
</label>
<label class="btn btn-default">
<input type="radio" name="radio-popup-position" class="radio-popup-style">button-3
</label>
<label class="btn btn-default">
<input type="radio" name="radio-popup-position" class="radio-popup-style">button-4
</label>
JS:
var aEls = $('.radio-popup-style-rect');
aEls.prop('checked', false).parent().removeClass('active');
aEls.eq(0).prop('checked', true).parent().addClass('active');
$("body").on("click", "label.btn", function(){$(this).find("input")[0].click();});