简体   繁体   English

JQuery:单击radiobutton时更改类

[英]JQuery: Change class when radiobutton is clicked

I need some help with javascript. 我需要一些javascript的帮助。

Here is the link to the code in JSFIDDLE: http://jsfiddle.net/Gopher69/B98kZ/4/ 这是JSFIDDLE中代码的链接: http//jsfiddle.net/Gopher69/B98kZ/4/

My JS is: 我的JS是:

$(document).ready(function() {
//add the Selected class to the checked radio button
$('[type=radio]').parent().addClass("selected");
//If another radio button is clicked, add the select class, and remove it from the       previously selected radio
$('input').click(function() {
    $('input:not(:checked)').parent().removeClass("radio  validate-one-required-by-name product-custom-option").find("class").html("radio  validate-one-required-by-name product-custom-option");
    $('input:checked').parent().addClass("radio  validate-one-required-by-name product-custom-option").find("class").html("radio  validate-one-required-by-name product-custom-option active");
});});

I want to adjust the the background color for the radio buttons just like I did with the hover effect with css. 我想调整单选按钮的背景颜色,就像我用css悬停效果一样。 So I need to add something like "checked" to the class when the radiobutton is active. 因此,当radiobutton处于活动状态时,我需要向类中添加类似“已检查”的内容。

I found this post but I'm juts not getting foreword: jQuery Checkbox selection and change class 我找到了这篇文章,但我没有得到前言: jQuery Checkbox选择和更改类

If somebody could help me out, I would be very thankfull. 如果有人可以帮助我,我会非常感激。

you can use pure css to do this: 你可以使用纯css来做到这一点:

  input[type="radio"]:checked {
    /* put some style here */
  }
$("#" + radioelementid).on("change",function(){  
$(this).addClass("testClass")   
//or   
$(this).removeClass("testClass");
});

Based on @Krunal Goswami's answer - even shorter: 根据@Krunal Goswami的回答 - 更短:

$("#" + elementId).on("change",function(){
    $(this).toggleClass("checked");
});

Note 注意

That should do your trick. 那应该是你的伎俩。 Although I don't recommend using this. 虽然我不建议使用这个。 Instead try a 'custom checkbox' implementation / jQuery plugin since native browser checkboxes don't really like being styled (cross browser). 而是尝试“自定义复选框”实现/ jQuery插件,因为本机浏览器复选框并不真正喜欢被设置样式(跨浏览器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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