jquery在选择单选按钮上应用css类

我有3个单选按钮。我需要做的是,当选择一个单选按钮时,我需要在文本之后应用我的css类名称“line”

  Milk  

我需要在Milk上应用我的课程,当用户选择其他单选按钮时,同一课程适用于其他单选按钮文本,但删除前一个课程。这是我试过的

  .line{ text-decoration: line-through; }   $(document).ready(function(){ $("input[type='radio']").change(function(){ if($(this).is(':checked')) //i wana do this $(this).addClass('line'); //if another is selected so do this $(this).removeClass('line'); }); }); 

  
Milk
Butter
Cheese

由于您需要将类添加到span ,因此可以使用parent从单选按钮访问span 。 要从其他span元素中删除该类,只需将该类从具有相关类的所有类中删除,然后再将该类添加到刚刚选择的span中:

 $("input[type='radio']").change(function() { if(this.checked) { $('span.line').removeClass('line'); $(this).parent().addClass('line'); } }); 

这是一个有效的例子 。

注意使用this.checked而不是你拥有的jQuery版本。 在可能的情况下使用本机DOM属性要快得多。

 $("input[type='radio']").change(function() { console.log(this.checked) if (this.checked) { // remove previously added line class $('span.line').removeClass('line'); // you should add class to span, because text is // within span tag, not in input $(this).parent().addClass('line'); } }); 

工作样本