单击图标时添加和删除类

时间:2014-05-28 13:23:08

标签: javascript jquery html css

我有两种类型的图标:

icon- {payment_system_name} - 灰色 icon- {payment_system_name} -active - active

这看起来像我的html:

<div id="vtb24-banking" class="inline-block space-sides-big">
   <input type="radio" name="payment_system" id="VTB24" value="VTB24">
   <label for="VTB24"><div class="icon icon-vtb24 pointer payment-logo"></div></label>
   <div id="vtb24-price" class="price"><span>500</span> руб.</div>
</div>
<div id="rsbbank-banking" class="inline-block space-sides-big">
   <input type="radio" name="payment_system" id="RSB" value="RSB">
   <label for="RSB"><div class="icon icon-rsbbank pointer payment-logo"></div></label>
   <div id="rsbbank-price" class="price"><span>500</span> руб.</div>
</div>
<div id="alfa-banking" class="inline-block space-sides-big">
   <input type="radio" name="payment_system" id="ALFACLICK" value="ALFACLICK">
   <label for="ALFACLICK"><div class="icon icon-alfa pointer payment-logo"></div></label>
   <div id="alfa-price" class="price"><span>500</span> руб.</div>
</div>

我的任务是 - 点击付款系统图标时 - 它应该是有效的,有些是灰色的。

我的jquery代码:

$('.payment-logo').click(function() {
   var paymentId = $(this).parent().parent().attr('id').split('-');
   $(this).addClass('icon-'+paymentId[0]+'-active');
});

但它只添加了活动图标类。如何从其他支付系统中删除活动类?

3 个答案:

答案 0 :(得分:0)

$('.payment-logo').click(function() {
    $('.payment-logo').each(function() {
        var paymentId = $(this).parent().parent().attr('id').split('-');
        $(this).removeClass('icon-'+paymentId[0]+'-active');
    });
    var paymentId = $(this).parent().parent().attr('id').split('-');
    $(this).addClass('icon-'+paymentId[0]+'-active');
});

答案 1 :(得分:0)

EleremoveClass(“类名”)从元素中删除任何CSS类。

答案 2 :(得分:0)

我认为您的方法使您实现目标的方式变得复杂。

如果你可以自定义一些css类,你可以这样简化任务:

Fiddle

CSS

.icon-alfa{
 /* your usual style */
}

.icon-alfa.is-active{
 /* the new style currently associated to icon-alfa-active */
}

/* and so for the other payment methods */

//then with JavaScript will be as simple as:

$('.payment-logo').on("click", function () {
   $('.payment-logo.is-active').removeClass('is-active');
   $(this).addClass('is-active');
});