简体   繁体   English

如果选中复选框,则更改类bg

[英]Change class bg if checkbox is checked

I'm working on my portfolio website and need some help with a bit jQuery code. 我正在我的投资组合网站上工作,并且需要一些jQuery代码帮助。 I want a parent class to react to the checkbox in it. 我希望父类对其中的复选框做出反应。 In this case, the background color needs to change to #000 when the checkbox is active/checked. 在这种情况下,当复选框处于活动/选中状态时,背景色需要更改为#000

I don't know what line of code to add to make my class react to the checkbox. 我不知道要添加什么代码行来使我的班级对复选框做出反应。 I've searched on google on how to do it but didn't get much wiser. 我已经在Google上搜索了如何执行此操作,但没有变得更明智。 It's probably a really small thing but I would hope to get some help from you guys. 这可能是一件很小的事,但我希望能从你们那里得到一些帮助。

 $("input[type='checkbox']").change(function() { if ($(this).is(":checked")) { $(this).parent(); } else { $(this).parent(); } }); 
 .product { background-color: #ccc; /* needs to change to #000 when active */ } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <div class="product"> <input class="check" type="checkbox" name="logo"> Logo </div> 

Basically you create a second (more specific) css selector for the active state, then you use your jQuery to toggle that state/class based on the checkbox value. 基本上,您为活动状态创建了第二个(更具体的)css选择器,然后使用jQuery根据复选框的值切换该状态/类。

https://jsbin.com/betafupogu/1/edit?html,css,js,output https://jsbin.com/betafupogu/1/edit?html,css,js,output

CSS CSS

.product {
  background-color: #ccc; /* needs to change to #000 when active */
}

.product.active {
  background-color: #000; 
}

jQuery jQuery的

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script>

        $("input[type='checkbox']").change(function(){
    if($(this).is(":checked")){
        $(this).parent().addClass('active'); 
    }else{
        $(this).parent().removeClass('active'); 
    }
});

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM