繁体   English   中英

jQuery在单选按钮上的选择上应用css类

[英]jquery applying css class on select on radio buttons

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

  <span> <input type="radio" name="group1" value="Milk">  Milk </span> 

我需要在Milk上应用我的课程,并且当用户选择其他单选按钮时,因此同一课程适用于其他单选按钮文本,但从上一个课中删除课程。这就是我尝试的

<style type="text/css">
    .line{
        text-decoration: line-through;
         }
</style>

<script type="text/javascript">
$(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');
      });
   });

 <div>
  <span> <input type="radio" name="group1" value="Milk">  Milk </span> </br>
  <span> <input type="radio" name="group1" value="Butter"> Butter </span> </br>
  <span> <input type="radio" name="group1" value="Cheese"> Cheese </span> </br>
  <hr>
</div>

由于需要将类添加到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');
    }
});

工作样本

暂无
暂无

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

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