我有两组独立的单选按钮,我希望它的"div"颜色在被选中时发生变化。我想要的行为非常简单,如果选择了单选按钮,相应的div应该会改变颜色。(如果取消选择,则更改回其原始颜色)。
然而,问题是,如果选择了另一个集合中的单选按钮,则第一个集合的div将变回其原始颜色,即使其中一个单选按钮仍处于选中状态。我该如何解决这个问题?
点击此处查看演示
使用的Jquery:
$(document).ready(function(){
$('input:radio').change(function(){
$('div.highlight').removeClass('highlight');
$(this).closest('div').addClass('highlight');
});
});
对于第二个问题,您需要将块的输入包装到一个单独的包装器中,并更改一些代码。。
JS
$(document).ready(function(){
$('input:radio').change(function(){
var $this = $(this);
// Only remove the class in the specific `box` that contains the radio
$this.closest('.box').find('div.highlight').removeClass('highlight');
$this.closest('.q').addClass('highlight');
});
});
HTML
<div class="box"> 1st set
<div class="q">
<input type="radio" id="1" name="11" />
<label for 1>a</label>
</div>
<div class="q">
<input type="radio" id="2" name="11" />
<label for 2>b</label>
</div>
</div>
<div class="box">
<hr> 2nd set
<div class="q">
<input type="radio" id="3" name="22" />
<label for 3>a</label>
</div>
<div class="q">
<input type="radio" id="4" name="22" />
<label for 4>b</label>
</div>
</div>
检查Fiddle
不是jQuery,但您可以查看css规则(嵌套很重要:div.highlight和radio需要是兄弟):
以下的Dabblet示例
div.entry {
position: relative;
padding: 8px;
width: 50%;
}
div.entry div.highlight {
background-color: #fff;
position: absolute;
z-index: -1;
top: 0px;
right: 0px;
bottom: 0px;
left: 0px;
}
div.entry input:checked ~ div.highlight {
background-color: orange;
}
<div class="entry">
<input type="radio" name="list" />This is one option
<div class="highlight"></div>
</div>
<div class="entry">
<input type="radio" name="list" />This is another option
<div class="highlight"></div>
</div>
<div class="entry">
<input type="radio" name="list" />This is a third option
<div class="highlight"></div>
</div>