【问题标题】:Jquery to change div background color when radio button selected?Jquery在选择单选按钮时更改div背景颜色?
【发布时间】:2013-07-31 23:02:20
【问题描述】:

我有两组独立的单选按钮,我希望它的“div”颜色在被选中时改变。 我想要的行为很简单,如果选择了单选按钮,相应的 div 应该改变颜色。 (如果取消选择,则更改回原来的颜色)。

但是,问题在于,如果选择了另一组中的单选按钮,则即使其中一个单选按钮仍处于选中状态,第一组的 div 也会变回其原始颜色。我该如何解决这个问题?

See demo here

使用的jQuery:

$(document).ready(function(){
    $('input:radio').change(function(){
        $('div.highlight').removeClass('highlight');
        $(this).closest('div').addClass('highlight');
    });
});

【问题讨论】:

  • 你忘记添加 jQuery 框架了。检查这个jsfiddle.net/sushanth009/wCNAp/1
  • @Sushanth--你为什么不把这个作为答案呢?因为它是 xD
  • 糟糕,已解决,但我的问题仍然存在

标签: jquery css


【解决方案1】:

对于第二个问题,您需要将块的输入包装到单独的包装器中并更改一些代码..

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>

Check Fiddle

【讨论】:

    【解决方案2】:

    不是 jQuery,但您可以查看 css 规则(嵌套很重要:div.highlight 和 radio 需要是兄弟姐妹):

    Dabblet example of below

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 2015-01-03
      • 2012-11-08
      • 2013-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-05-30
      相关资源
      最近更新 更多