[英]Bootstrap - btn-group, data-toggle=“buttons” : how to select a button with JS and deselect all others?
嗨,我正在使用Bootstrap的.btn-group類,如下所示:
<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');
});
關於屬性選擇器中的 正則表達式 : http : //www.thegeekyway.com/css-regex-selector-using-regular-expression-css/ 。
您可以使用內置的 BS方法切換按鈕狀態:
(您需要頁面上的默認button.js)
https://github.com/twbs/bootstrap/blob/master/js/button.js#L52-L66 http://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();});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.