当单选按钮被点击时改变类

JQuery: Change class when radiobutton is clicked

本文关键字:改变 单选按钮      更新时间:2023-09-26

我需要一些javascript的帮助。

下面是JSFIDDLE中代码的链接:http://jsfiddle.net/Gopher69/B98kZ/4/

我的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");
});});

我想调整单选按钮的背景颜色,就像我对css的悬停效果所做的那样。因此,当单选按钮处于活动状态时,我需要向类添加类似"checked"的内容。

我发现了这篇文章,但我只是没有得到前言:jQuery复选框选择和改变类

如果有人能帮我,我将非常感激。

你可以使用纯CSS:

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

根据@Krunal Goswami的回答-甚至更短:

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

注意

那应该能达到你的目的。虽然我不建议使用这个。相反,尝试一个"自定义复选框"实现/jQuery插件,因为本地浏览器的复选框不喜欢样式(跨浏览器)。