简体   繁体   中英

add and remove class when clicking on icons

I have two types of icons:

icon-{payment_system_name} - grey icon-{payment_system_name}-active - active

This how look like my 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>

My task is - when clicking on payment system icon - it should be active, others grey.

My jquery code:

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

but its only adding active icon class. How i can do the removing active classes from other payment systems?

$('.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');
});

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

I think that your approach is complicating the way you accomplish your target.

If you can customize a little the css classes, you can simplify the task this way:

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM