我尝试通过使用以下代码单击先前选择的按钮来使 Bootstrap btn-group 不可选择:
$(document).ready(function() {
$('label.btn').click(function(e) {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="note_reactivity" class="btn-group notes" data-toggle="buttons">
<label id="1" class="btn btn-primary">
<input type="radio">1
</label>
<label id="2" class="btn btn-primary">
<input type="radio">2
</label>
<label id="3" class="btn btn-primary">
<input type="radio">3
</label>
<label id="4" class="btn btn-primary">
<input type="radio">4
</label>
</div>
“事件”类似乎被我的点击事件代码删除,但它随后又重新出现。 你知道该怎么做吗?
最佳答案
您的代码不起作用,因为元素上仍然附加了底层 Bootstrap 单击事件处理程序,该处理程序会在您将其取下后立即将 active
类放回到元素上。为了解决这个问题,您可以在代码上设置一个微小的延迟,以确保它在 Bootstrap 完成自己的事情之后发生。
另请注意,您需要手动取消选择底层单选按钮并删除该类。试试这个
$(document).ready(function() {
$('.btn-group').on('click', 'label.btn', function(e) {
if ($(this).hasClass('active')) {
setTimeout(function() {
$(this).removeClass('active').find('input').prop('checked', false);
}.bind(this), 10);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div id="note_reactivity" class="btn-group notes" data-toggle="buttons">
<label id="1" class="btn btn-primary">
<input type="radio">1
</label>
<label id="2" class="btn btn-primary">
<input type="radio">2
</label>
<label id="3" class="btn btn-primary">
<input type="radio">3
</label>
<label id="4" class="btn btn-primary">
<input type="radio">4
</label>
</div>
关于jquery - 如何在 Bootstrap btn-group 中单击时取消选择按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36480350/