在第二次单击时取消选择bootstrap 3单选按钮

Dej*_*ell 3 html javascript css jquery twitter-bootstrap

我想允许取消选择引导btn-group单选按钮,而无需额外的按钮。

按照这个答案,我写了jsfiddle,但对我不起作用。为什么?通过查看日志,可以看到第二次单击该方法。

$('body').on('click', '.btn.active', function(e){
    console.log("test");
    e.stopImmediatePropagation();
    $('input:radio[name="options"]').parent().removeClass("active");
})
Run Code Online (Sandbox Code Playgroud)

HTML:

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary active">
        <input type="radio" name="options" id="option1" autocomplete="off" checked/>Radio 1 (preselected)
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2" autocomplete="off">Radio 2
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3" autocomplete="off">Radio 3
    </label>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

这是工作中的小提琴。由于某些原因,您必须同时调用stopPropagate和preventDefault才能使其正常工作。

$('body').on('click', '.btn.active', function(e){
    e.stopImmediatePropagation();
    e.preventDefault();
    console.log(this, $('input:radio[name="options"]', this));
    $(this).removeClass('active');
    $('input:radio[name="options"]', this).prop('checked', false);
})
Run Code Online (Sandbox Code Playgroud)