选中复选框后更改父级的背景

时间:2015-11-28 17:39:50

标签: javascript jquery css checkbox

我正在尝试在选中复选框时更改复选框的父元素的背景。

这是我的JS:



#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label {
  display: block;
  background: #C99C49;
  margin: 10px 0;
  cursor: pointer;
  padding: 20px;
}
.checked-checkbox-parent {
  background: black;
}

<label for="one-month">
  <input id="one-month" type="checkbox">
  <span>Monthly</span>
  <span class="pull-right">(£30/case)</span>
  <div class="clearfix"></div>
</label>
&#13;
try...except
&#13;
&#13;
&#13;

在chrome上的DOM查看器中,事情就像我期望的那样:

表格&gt;标签&gt;复选框

因此,当我运行我的JS并选中一个复选框时,我希望标签的背景属性变为黑色,当未选中时,我希望它恢复正常。

1 个答案:

答案 0 :(得分:1)

$(document).ready(function() {
  $('#one-month').change(function(e) {
    if ($(this).prop("checked")) {
      $(this).parent().addClass('checked-checkbox-parent');
    } else {
      $(this).parent().removeClass('checked-checkbox-parent');
    }
  });
});
#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label input[type="checkbox"] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
#delivery-address-edit-modal .modal-dialog .modal-content .modal-body form label {
  display: block;
  background: #C99C49;
  margin: 10px 0;
  cursor: pointer;
  padding: 20px;
}
.checked-checkbox-parent {
  background: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="one-month">
  <input id="one-month" type="checkbox">
  <span>Monthly</span>
  <span class="pull-right">(£30/case)</span>
  <div class="clearfix"></div>
</label>