简体   繁体   English

选中复选框后,如何更改DIV的颜色?

[英]How do I change the color of my DIV when checkbox is checked?

I want to change the color of the DIV when a checkbox is checked. 选中复选框后,我想更改DIV的颜色。 I want to do this in jQuery. 我想在jQuery中做到这一点。 I have tried this : 我已经试过了:

 if($('#checkboxTest').is(':checked'))
    {
        $('.alertWrapper').css('background-color', 'blue');
    }

But it is not working.. any help? 但是它不起作用..有什么帮助吗?

You need to use .change() event to keep track of the state of your checkbox: 您需要使用.change()事件来跟踪复选框的状态:

$('#checkboxTest').change(function() {
    if($(this).is(':checked'))
    {
        $('.alertWrapper').css('background-color', 'blue');
    } else {
        // Your code here will fired when the checkbox is unchecked
    }
}).change(); // <-- Trigger the change event on page load

You need to use change event : 您需要使用change事件:

$('#checkboxTest').change(function() {
   var c = this.checked ? 'blue' : 'transparent';
   $('.alertWrapper').css('background-color', c);
});

Working demo 工作演示

You can use the following (with click event): 您可以使用以下内容(带有click事件):

$('#checkboxTest').click (function ()
{
 var thisCheck = $(this);
 if (thischeck.is (':checked'))
 {
  // your stuff
 }
});

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

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