我试图切换活跃的'单击收音机/标签时,在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;
JSFiddle:https://jsfiddle.net/5vnhgduh/
答案 0 :(得分:2)
您可以将类添加到父级,并从父级的兄弟姐妹中删除类。
$('.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;
答案 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
});
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;