我想在父div
上选择收音机时添加green_bg
课程
<div class="content red_bg">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
</div>
<div class="content red_bg">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
</div>
<div class="content red_bg">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
</div>
和我的jquery
$(document).ready(function() {
$('input[type="radio"]').click(function() {
$(".content").removeClass("red_bg").addClass("green_bg");
});
});
但是当我选择收音机时,所有背景都变为绿色请帮帮我。
答案 0 :(得分:3)
仅选择所点击按钮的父.content
:
$('input[type="radio"]').click(function() {
$(this).closest(".content").removeClass("red_bg").addClass("green_bg");
});
或者,如果您还想重置所有其他人:
$('input[type="radio"]').click(function() {
$('.content').addClass('red_bg').removeClass('green_bg');
$(this).closest(".content").removeClass("red_bg").addClass("green_bg");
});
示例:
$('input[type="radio"]').click(function() {
$('.content').addClass('red_bg').removeClass('green_bg');
$(this).closest(".content").removeClass("red_bg").addClass("green_bg");
});
&#13;
.green_bg {
background-color: green;
}
.red_bg {
background-color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content red_bg">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
</div>
<div class="content red_bg">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
</div>
<div class="content red_bg">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
<input type="radio" name="answerkey" id="ankeya2" value="option2">
</div>
&#13;
答案 1 :(得分:0)
试试这个..
$(document).ready(function() {
$('input[type="radio"]').click(function() {
$(this).parent().removeClass("red_bg").addClass("green_bg");
});
});