如果选中单选按钮,则更改父div的背景颜色

时间:2018-03-13 23:14:00

标签: javascript jquery html

我在选中按钮时尝试更改包含单选按钮的div的背景颜色。

这是html

  <div class="testing-container">
            <input id=“test” type="radio" name="option-{{ option_index }}" value=“test”/>
          <label for="swatch">
         Test
        </label>
      </div>

我已经尝试过像这样的jquery

  $(".testing-container input").change(function() { 
    if ($(this).is(":checked")) {
        $(this).parent().css("background", "black");
    }
});

2 个答案:

答案 0 :(得分:0)

您的目标是错误的元素。您的html类为testing-container,而在您的jQuery中,您的目标是test-container inputtest-container vs testing-container

编辑2

此外,您的HTML中的引号实际上并不是引号。它们是看起来像引号的其他字符。

编辑3

由于您已修复这些问题,因此应解决您的问题。这是一个包含您确切代码的代码段。

&#13;
&#13;
$(document).ready(function() {
  $(".testing-container input").change(function() {
    if ($(this).is(":checked")) {
      $(this).parent().css("background", "black");
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="testing-container">
	<input id=“test” type="radio" name="option-{{ option_index }}" value=“test”/>
	<label for="swatch">
		Test
	</label>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在这里放置我的解决方案,以防万一有人遇到我遇到的同一问题。

尝试设置所选单选按钮的父li标签的背景颜色。我想出了以下JQuery解决方案。

我的HTML看起来像这样:

<li class="zb-list-group-item pl-3">
      <div class="custom-control custom-radio">
         <input type="radio" id="shippingMethod_2_2_1_1" name="shippingMethod_2_2_1" class="custom-control-input submit-radio" value="4|1 day shipping|Priority Mail Express|0|0|0.0000">
         <label class="custom-control-label" for="shippingMethod_2_2_1_1">
         <span class="d-block text-success font-weight-bold">Tuesday Jan 08, 2019</span>
         <span class="d-block">$0.00 - 3-5 day shipping</span>
         </label>
      </div>
   </li>

不仅需要触发单选按钮更改事件,而且还需要在页面加载时设置背景颜色。

JQuery看起来像这样:

$(document).ready(function() {

  // Find and select background color of selected shipping option parent li
    $(".custom-control-input:checked").each(function () {
    $('.zb-list-group-item.highlight').removeClass('highlight');
    $(this).closest('.zb-list-group-item').addClass('highlight');
  });

  // On change of shipping options change background color of parent li
  $('.custom-control-input').on("change", function () {
    // Only remove the class in the specific `box` that contains the radio
    $('.zb-list-group-item.highlight').removeClass('highlight');
    $(this).closest('.zb-list-group-item').addClass('highlight');
  });

});

工作的JSFiddle可以在这里找到: https://jsfiddle.net/kbLxwdr2/1/

希望这可以帮助某人:)

相关问题