2016-04-07 49 views
2

我试图做一个引导BTN-组不可选择通过点击下面的代码从先前所选择按钮:如何在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>

“激活”类似乎是我的代码上去除点击事件,但它刚刚重新出现。 你知道该怎么做吗?

回答

5

您的代码无法正常工作,因为仍然存在附加到该元素的基础引导程序单击事件处理程序,该元素将在您关闭后立即将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>

+0

非常感谢你它的工作! – Vincent

+0

没问题,很乐意帮忙。 –

+0

也为我工作。这让我非常高兴和非常难过,因为这很难。 :-) – moodboom

相关问题