jQuery切换类标签onclick上的无线电

时间:2017-02-17 12:59:38

标签: jquery html toggle

我试图切换活跃的'单击收音机/标签时,在2个标签上分类。因此,在页面加载时,检查第一个无线电,并且该无线电的标签具有“激活”等级。然后,如果你点击另一个收音机/标签,它将切换活动类。我几乎让它工作,我只是做了一些稍微错误的事情。



$('.label_item input[type="radio"]').click(function() {
  if (!$(this).is(':checked')) {
    $(this).parent('.label_item').addClass('active');
  } else {
    $(this).parent('.label_item').removeClass('active');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label class="label_item active" for="a1">
<input type="radio" name="radio" id="a1" checked="checked" />label one</label>

<label class="label_item" for="a2">
<input type="radio" name="radio" id="a2" />label two</label>
&#13;
&#13;
&#13;

JSFiddle:https://jsfiddle.net/5vnhgduh/

2 个答案:

答案 0 :(得分:2)

您可以将类添加到父级,并从父级的兄弟姐妹中删除类。

&#13;
&#13;
$('.label_item input[type="radio"]').click(function() {
  $(this).parent().addClass('active').siblings('label').removeClass('active')
});
&#13;
.active {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label_item active" for="a1">
  <input type="radio" name="radio" id="a1" checked="checked" />label one</label>

<label class="label_item" for="a2">
  <input type="radio" name="radio" id="a2" />label two</label>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您需要在active单选按钮上添加:checked课程,我建议您使用change个活动。

var elements = $('.label_item :radio').change(function() {
    elements  //Select radio
      .parent().removeClass('active') //target parents and remove class
      .end() //target radio options 
      .filter(':checked') //get checked radio
      .parent().addClass('active'); //add class
});

&#13;
&#13;
var elements = $('.label_item :radio').change(function() {
  elements //Select radio
    .parent().removeClass('active') //target parents and remove class
    .end() //target radio options 
    .filter(':checked') //get checked radio
    .parent().addClass('active'); //add class
});
&#13;
.active {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="label_item active" for="a1">
    <input type="radio" name="radio" id="a1" checked="checked" />label one</label>

<label class="label_item" for="a2">
    <input type="radio" name="radio" id="a2" />label two</label>
&#13;
&#13;
&#13;

DEMO