Javascript 单击图标时添加和删除类
我有两种类型的图标: 图标-{支付系统名称}-灰色 图标-{付款系统名称}-活动-活动 这看起来像我的html:Javascript 单击图标时添加和删除类,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有两种类型的图标: 图标-{支付系统名称}-灰色 图标-{付款系统名称}-活动-活动 这看起来像我的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
<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>
但它只是添加了活动图标类。如何从其他支付系统中删除活动类?EleremoveClass(“类名”)从元素中删除任何CSS类。我认为您的方法使您实现目标的方式变得复杂
$('.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');
});
如果您可以自定义一点css类,则可以通过以下方式简化任务:
CSS
您可以转到并在那里设置您的项目,这样我们就可以看到它的行为。paymentId在每个支付系统上都是不同的
$('.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');
});
.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');
});