admin管理员组

文章数量:1309921

I am new to jQuery. I am trying to make a switcher using a checkbox. At the moment I have gone this far

$(function() {
  $('input.cbx').on('change', function() {
    if ($(this).prop("checked", true)) {
      $('body').addClass('dark');
    } else if ($(this).prop("checked", false)) {
      $('.body').addClass('light');
    }
  });
});
<script src=".1.1/jquery.min.js"></script>

<input id="dn" type="checkbox" class="cbx hidden" />
<label for="dn" class="lbl"></label>

I am new to jQuery. I am trying to make a switcher using a checkbox. At the moment I have gone this far

$(function() {
  $('input.cbx').on('change', function() {
    if ($(this).prop("checked", true)) {
      $('body').addClass('dark');
    } else if ($(this).prop("checked", false)) {
      $('.body').addClass('light');
    }
  });
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="dn" type="checkbox" class="cbx hidden" />
<label for="dn" class="lbl"></label>

As you can see the checkbox stay checked after the first click, I imagine is a noob situation but, can you help me please?

Share Improve this question edited Sep 21, 2015 at 11:39 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Sep 21, 2015 at 11:24 Nicola BertelloniNicola Bertelloni 3331 gold badge3 silver badges17 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You are actually setting the checked property instead of getting.

$('input.cbx').on('change', function() {
    if($(this).prop("checked") ==  "true")
    {
      $('body').addClass('dark');
    } else if($(this).prop("checked") ==  "false")
    {
        $('.body').addClass('light');
    }
});

You can use this.checked or $(this).is(":checked") instead of $(this).prop("checked")

$('input.cbx').on('change', function() {
    if(this.checked) 
       $('body').addClass('dark');
    else
       $('.body').addClass('light');        
});

You can also use toggleClass

$('input.cbx').on('change', function() {     
     $('.body').toggleClass('light');        
});

Note: I could not see any element with class body? You probably need to assign class to label. If you want to apply the toggle effect to body then remove dot

Live Demo

HTML

<body class="cbx">
<input id="dn" type="checkbox" class="cbx hidden"/>
      <label for="dn" class="lbl">123</label>
</body>

Javascript

$('input.cbx').on('change', function() {     
     $('body').toggleClass('light');        
});
$('input.cbx').on('change', function () {
    if ($(this).is(":checked")) {
        alert('checked');
    } else {
        alert('not checked');
    }
});

DEMO You can check if the checkbox is check using $(this).is(":checked")

本文标签: javascriptTrigger checkbox change class in JqueryStack Overflow