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