addClass,removeClass,如果hasClass问题

时间:2012-11-14 23:17:58

标签: jquery

我有3组按钮,其行为类似于单选按钮。

单选按钮工作正常,但我需要删除ID为#filter1-none的按钮的活动类,如果任何其他按钮具有活动类。最好的方法是if / then解决方案,还是我可以用.filter做到这一点?

这是无线电行为。

$('.filter .btn').click(function () {
    $(this).addClass('active').siblings('.active').removeClass('active');
});

这是html:

<div class="btn-group pull-right filter" data-toggle="buttons-radio">
    <button type="button" class="btn btn-large btn-flat" id="filter1-none">Show All</button>
</div>

<div class="btn-group pull-right mr filter" data-toggle="buttons-radio">
    <button type="button" class="btn btn-large btn-flat" id="filter1-LI">LI</button>
    <button type="button" class="btn btn-large btn-flat" id="filter1-LPO">LPO</button>
    <button type="button" class="btn btn-large btn-flat" id="filter1-NLI">NLI</button>
</div>

<div class="btn-group pull-right mr filter" data-toggle="buttons-radio">
    <button type="button" class="btn btn-large btn-flat" id="filter1-Low">Low</button>
    <button type="button" class="btn btn-large btn-flat" id="filter1-Medium">Medium</button>
    <button type="button" class="btn btn-large btn-flat" id="filter1-Urgent">Urgent</button>
</div>

3 个答案:

答案 0 :(得分:1)

  $('.filter .btn').click(function () {
        $('#filter1-none').removeClass('active');
        $(this).addClass('active').siblings('.active').removeClass('active');
    });

答案 1 :(得分:0)

我不确定我是否理解正确,但要知道是否还有其他带有'active'类的元素,为什么不检查选择器返回的数组是否有任何元素?

if ($('.active').length > 1) {
    // There are two elements with the 'active'
    // class. One of them is the button with id
    // filter1-none
    $('#filter1-none').removeClass('active');
}

答案 2 :(得分:0)

如果我理解正确,这就是你想要的javascript。如果您单击的按钮不是#filter1-none,请从中删除活动类

var $none = $('#filter1-none');
$('.filter .btn').click(function () {
   $none.removeClass('active');
   $(this).addClass('active').siblings('.active').removeClass('active');
});​
相关问题