Если я правильно понимаю вопрос, вы хотите просто переключать кнопки вроде переключателей без использования переключателей.
Вы можете установить этот код ниже сценария начальной загрузки, чтобы отменить любые значения по умолчанию в файле после его прочтения.HTML читается сверху вниз, поэтому ваш файл будет выглядеть примерно так.
Используя ваш код, я добавил класс «remove-active» к обеим кнопкам и removeClass к вашему javascript.Вы все делали правильно, вам просто нужно превзойти начальные действия по умолчанию.По умолчанию, когда-то переключалось, необходимо переключиться, чтобы выйти из активного состояния.
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<button class="btn btn-outline-primary remove-active" id="1kgbtn" type="button" data-toggle="collapse" data-target="#1kgpack" aria-expanded="false" aria-controls="collapseExample" aria-pressed="false" autocomplete="off">
1kg package
</button>
<button class="btn btn-outline-primary remove-active" id="25kgbtn" type="button" data-toggle="collapse" data-target="#25kgpack" aria-expanded="false" aria-controls="collapseExample" aria-pressed="false" autocomplete="off">
2.5kg package
</button>
</div>
<script src="bootstrap.min.js"></script>
<script>
$('#1kgbtn').on('click', function () {
$('#25kgpack').collapse('hide')
$('.remove-active').removeClass('active');
if ($('#25kgbtn').button('active') == true) {
$('#1kgbtn').button('toggle');
}
});
$('#25kgbtn').on('click', function () {
$('#1kgpack').collapse('hide');
$('.remove-active').removeClass('active');
if ($('#1kgbtn').button('active') == true) {
$('#25kgbtn').button('toggle');
}
});
</script>
Используя целевой объект данных, вы можете получить идентификатор и позже с ним делать разные вещи.(эта часть просто классная)
$('button[data-toggle="collapse"]').click(function(){
//log the id of the target
console.log($(this).attr('data-target'));
});
Надеюсь, это поможет.
- редактировать -
Я немного изменил код, но сделал комментарии, чтобы помочь с объяснением.
//on button click
$('button').click(function(e){
//the current button is toggled
//check to see if the other button is toggled
if($('.remove-active').hasClass('active')){ //if it has class this means it is active
//store the active id
var e = $('.remove-active.active').attr('id');
//we clicked on the same button then we would equal the same id
if(e == $(this).attr('id')){
//collapse the clicked Id if we are unpressing the button
$(this).collapse('hide');
console.log(e + ' auto toggles with bootstrap and collapse the currently clicked target ' + $(this).attr('data-target'));
}else{ // else
//we untoggle the other button and element
$('#' + e).button('toggle');
//we also collapse the other element
$($('#' + e).attr('data-target')).collapse('hide');
console.log("The other element was clicked and we cleared it along with collapsing the " + $('#' + e).attr('data-target'));
}
}
//be sure to close out the console.log() stuff
//this is just for viewing example
});
Это переключит текущую кнопку, проверит, переключена ли другая кнопка, и если это так, переключите ее.Также, если кнопка переключается, то при нажатии этой кнопки указанная кнопка затем отключается.