【问题标题】:jquery applying css class on select on radio buttonsjquery在单选按钮上的选择上应用css类
【发布时间】:2012-06-14 16:44:18
【问题描述】:

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 上申请我的课程 当用户选择其他单选按钮时,相同的类适用于其他单选按钮文本但从前一个单选按钮中删除类。这就是我尝试过的

<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>

【问题讨论】:

    标签: javascript jquery radio-button


    【解决方案1】:

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

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

    这是working example

    注意使用this.checked 而不是您拥有的jQuery 版本。尽可能使用原生 DOM 属性会快得多。

    【讨论】:

      【解决方案2】:
      $("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');
          }
      });
      

      Working sample

      【讨论】:

        猜你喜欢
        • 2011-02-07
        • 1970-01-01
        • 2018-11-27
        • 2012-06-28
        • 2014-07-02
        • 2017-01-26
        • 1970-01-01
        • 2016-02-25
        • 1970-01-01
        相关资源
        最近更新 更多