【问题标题】:How to add class to div based on radio button selected in it?如何根据其中选择的单选按钮向 div 添加类?
【发布时间】:2017-04-19 10:59:57
【问题描述】:

我已经编写了如下代码行的 html。

<div class="form-group">

    <div class="i-checks">
       <label class="col-sm-6 control-label"> 
         <div class="iradio_square-green" style="position: relative;">
         <input type="radio" value="name" name="checkchoice" style="position: absolute; opacity: 0;">
         <ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
         </div>
         Name
        </label>
     </div>

     <div class="i-checks">
       <label class="col-sm-6 control-label"> 
         <div class="iradio_square-green" style="position: relative;">
         <input type="radio" value="rollno" name="checkchoice" style="position: absolute; opacity: 0;">
         <ins class="iCheck-helper" style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
         </div>
         Roll No
        </label>
     </div>

</div>

现在我希望如果有人选择任何单选按钮然后在相应的 div &lt;div class="iradio_square-green" style="position: relative;"&gt; 应附加“已检查”类,如 &lt;div class="iradio_square-green checked" style="position: relative;"&gt;

我试过了

$(document).ready(function () {
  $(':radio').change(function () {
    $(':radio[name=' + this.name + ']').parent().removeClass('checked');
    $(this).parent().addClass('checked');
  });
});​

它不工作

【问题讨论】:

  • SO 不是免费的编码服务 - 所以请告诉我们您的尝试。
  • 之后显示您的代码将对您有所帮助...

标签: javascript jquery jquery-ui


【解决方案1】:

你可以用纯 CSS 做到这一点,不需要 JS(如果样式是你唯一的目标)

CSS:

input[type=checkbox]:checked ~ div {
    some styles....
}

理想情况下,您将在上面使用类名而不是标签名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2018-02-27
    • 2017-06-30
    • 2018-08-10
    相关资源
    最近更新 更多