jQuery在单选按钮上的选择上应用css类 [英] jquery applying css class on select on radio buttons

查看:76
本文介绍了jQuery在单选按钮上的选择上应用css类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个无线电buttons.what我需要做的是,当选择了一个单选按钮所以我需要它后对文本应用我的CSS类名线"等

i have 3 radio buttons.what i need to do is that when one radio button is selected so i need to apply my css class name "line" on the text after it like

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

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

i need to apply my class on Milk and when user select other radio button so the same class apply on other radio button text but remove class from the previous one.this is what i tried

<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,因此可以使用

Since you need to add the class to the span, you can use parent to access the span from the radio button. To remove the class from the other span elements, just remove it from all which have the class in question before adding the class to the span that was just selected:

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

这是一个工作示例.

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

Note the use of this.checked instead of the jQuery version you had. It is much faster to use the native DOM property where possible.

这篇关于jQuery在单选按钮上的选择上应用css类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆